source: src/GenPoly/Box.cc @ ae7014e

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 ae7014e was ae7014e, checked in by Aaron Moss <a3moss@…>, 8 years ago

Fix bug that forgets to add dtype mappings to assign op expression

  • Property mode set to 100644
File size: 101.2 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 <algorithm>
17#include <iterator>
18#include <list>
19#include <map>
20#include <set>
21#include <stack>
22#include <string>
23#include <utility>
24#include <vector>
25#include <cassert>
26
27#include "Box.h"
28#include "DeclMutator.h"
29#include "PolyMutator.h"
30#include "FindFunction.h"
31#include "ScopedMap.h"
32#include "ScopedSet.h"
33#include "ScrubTyVars.h"
34
35#include "Parser/ParseNode.h"
36
37#include "SynTree/Constant.h"
38#include "SynTree/Declaration.h"
39#include "SynTree/Expression.h"
40#include "SynTree/Initializer.h"
41#include "SynTree/Mutator.h"
42#include "SynTree/Statement.h"
43#include "SynTree/Type.h"
44#include "SynTree/TypeSubstitution.h"
45
46#include "ResolvExpr/TypeEnvironment.h"
47#include "ResolvExpr/TypeMap.h"
48#include "ResolvExpr/typeops.h"
49
50#include "SymTab/Indexer.h"
51#include "SymTab/Mangler.h"
52
53#include "Common/SemanticError.h"
54#include "Common/UniqueName.h"
55#include "Common/utility.h"
56
57#include <ext/functional> // temporary
58
59namespace GenPoly {
60        namespace {
61                const std::list<Label> noLabels;
62
63                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
64
65                /// Abstracts type equality for a list of parameter types
66                struct TypeList {
67                        TypeList() : params() {}
68                        TypeList( const std::list< Type* > &_params ) : params() { cloneAll(_params, params); }
69                        TypeList( std::list< Type* > &&_params ) : params( _params ) {}
70
71                        TypeList( const TypeList &that ) : params() { cloneAll(that.params, params); }
72                        TypeList( TypeList &&that ) : params( std::move( that.params ) ) {}
73
74                        /// Extracts types from a list of TypeExpr*
75                        TypeList( const std::list< TypeExpr* >& _params ) : params() {
76                                for ( std::list< TypeExpr* >::const_iterator param = _params.begin(); param != _params.end(); ++param ) {
77                                        params.push_back( (*param)->get_type()->clone() );
78                                }
79                        }
80
81                        TypeList& operator= ( const TypeList &that ) {
82                                deleteAll( params );
83
84                                params.clear();
85                                cloneAll( that.params, params );
86
87                                return *this;
88                        }
89
90                        TypeList& operator= ( TypeList &&that ) {
91                                deleteAll( params );
92
93                                params = std::move( that.params );
94
95                                return *this;
96                        }
97
98                        ~TypeList() { deleteAll( params ); }
99
100                        bool operator== ( const TypeList& that ) const {
101                                if ( params.size() != that.params.size() ) return false;
102
103                                SymTab::Indexer dummy;
104                                for ( std::list< Type* >::const_iterator it = params.begin(), jt = that.params.begin(); it != params.end(); ++it, ++jt ) {
105                                        if ( ! ResolvExpr::typesCompatible( *it, *jt, dummy ) ) return false;
106                                }
107                                return true;
108                        }
109
110                        std::list< Type* > params;  ///< Instantiation parameters
111                };
112
113                /// Maps a key and a TypeList to the some value, accounting for scope
114                template< typename Key, typename Value >
115                class InstantiationMap {
116                        /// Wraps value for a specific (Key, TypeList) combination
117                        typedef std::pair< TypeList, Value* > Instantiation;
118                        /// List of TypeLists paired with their appropriate values
119                        typedef std::vector< Instantiation > ValueList;
120                        /// Underlying map type; maps keys to a linear list of corresponding TypeLists and values
121                        typedef ScopedMap< Key*, ValueList > InnerMap;
122
123                        InnerMap instantiations;  ///< instantiations
124
125                public:
126                        /// Starts a new scope
127                        void beginScope() { instantiations.beginScope(); }
128
129                        /// Ends a scope
130                        void endScope() { instantiations.endScope(); }
131
132                        /// Gets the value for the (key, typeList) pair, returns NULL on none such.
133                        Value *lookup( Key *key, const std::list< TypeExpr* >& params ) const {
134                                TypeList typeList( params );
135                               
136                                // scan scopes for matches to the key
137                                for ( typename InnerMap::const_iterator insts = instantiations.find( key ); insts != instantiations.end(); insts = instantiations.findNext( insts, key ) ) {
138                                        for ( typename ValueList::const_reverse_iterator inst = insts->second.rbegin(); inst != insts->second.rend(); ++inst ) {
139                                                if ( inst->first == typeList ) return inst->second;
140                                        }
141                                }
142                                // no matching instantiations found
143                                return 0;
144                        }
145
146                        /// Adds a value for a (key, typeList) pair to the current scope
147                        void insert( Key *key, const std::list< TypeExpr* > &params, Value *value ) {
148                                instantiations[ key ].push_back( Instantiation( TypeList( params ), value ) );
149                        }
150                };
151
152                /// Adds layout-generation functions to polymorphic types
153                class LayoutFunctionBuilder : public DeclMutator {
154                        unsigned int functionNesting;  // current level of nested functions
155                public:
156                        LayoutFunctionBuilder() : functionNesting( 0 ) {}
157
158                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
159                        virtual Declaration *mutate( StructDecl *structDecl );
160                        virtual Declaration *mutate( UnionDecl *unionDecl );
161                };
162               
163                /// 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
164                class Pass1 : public PolyMutator {
165                  public:
166                        Pass1();
167                        virtual Expression *mutate( ApplicationExpr *appExpr );
168                        virtual Expression *mutate( AddressExpr *addrExpr );
169                        virtual Expression *mutate( UntypedExpr *expr );
170                        virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
171                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
172                        virtual Expression *mutate( CommaExpr *commaExpr );
173                        virtual Expression *mutate( ConditionalExpr *condExpr );
174                        virtual Statement * mutate( ReturnStmt *returnStmt );
175                        virtual Type *mutate( PointerType *pointerType );
176                        virtual Type * mutate( FunctionType *functionType );
177
178                        virtual void doBeginScope();
179                        virtual void doEndScope();
180                  private:
181                        /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
182                        void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
183                        /// passes extra type parameters into a polymorphic function application
184                        void passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
185                        /// wraps a function application with a new temporary for the out-parameter return value
186                        Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
187                        /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
188                        void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
189                        /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
190                        /// If `doClone` is set to false, will not clone interior types
191                        Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
192                        /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
193                        Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
194                        Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
195                        void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
196                        void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
197                        void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
198                        /// Stores assignment operators from assertion list in local map of assignment operations
199                        void findAssignOps( const std::list< TypeDecl *> &forall );
200                        void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
201                        FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
202                        /// Replaces intrinsic operator functions with their arithmetic desugaring
203                        Expression *handleIntrinsics( ApplicationExpr *appExpr );
204                        /// Inserts a new temporary variable into the current scope with an auto-generated name
205                        ObjectDecl *makeTemporary( Type *type );
206
207                        std::map< std::string, DeclarationWithType *> assignOps;     ///< Currently known type variable assignment operators
208                        ResolvExpr::TypeMap< DeclarationWithType > scopedAssignOps;  ///< Currently known assignment operators
209                        ScopedMap< std::string, DeclarationWithType* > adapters;     ///< Set of adapter functions in the current scope
210                       
211                        DeclarationWithType *retval;
212                        bool useRetval;
213                        UniqueName tempNamer;
214                };
215
216                /// * Moves polymorphic returns in function types to pointer-type parameters
217                /// * adds type size and assertion parameters to parameter lists
218                /// * does dynamic calculation of type layouts
219                class Pass2 : public PolyMutator {
220                  public:
221                        template< typename DeclClass >
222                        DeclClass *handleDecl( DeclClass *decl, Type *type );
223                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
224                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
225                        virtual TypeDecl *mutate( TypeDecl *typeDecl );
226                        virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
227                        virtual Type *mutate( PointerType *pointerType );
228                        virtual Type *mutate( FunctionType *funcType );
229                        virtual Expression *mutate( SizeofExpr *sizeofExpr );
230                        virtual Expression *mutate( AlignofExpr *alignofExpr );
231                        virtual Expression *mutate( OffsetofExpr *offsetofExpr );
232                        virtual Expression *mutate( OffsetPackExpr *offsetPackExpr );
233
234                        virtual void doBeginScope();
235                        virtual void doEndScope();
236                  private:
237                        void addAdapters( FunctionType *functionType );
238                        /// Makes a new variable in the current scope with the given name, type & optional initializer
239                        ObjectDecl *makeVar( const std::string &name, Type *type, Initializer *init = 0 );
240                        /// returns true if the type has a dynamic layout; such a layout will be stored in appropriately-named local variables when the function returns
241                        bool findGeneric( Type *ty );
242                        /// adds type parameters to the layout call; will generate the appropriate parameters if needed
243                        void addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams );
244
245                        std::map< UniqueId, std::string > adapterName;
246                        ScopedSet< std::string > knownLayouts;          ///< Set of generic type layouts known in the current scope, indexed by sizeofName
247                        ScopedSet< std::string > knownOffsets;          ///< Set of non-generic types for which the offset array exists in the current scope, indexed by offsetofName
248                };
249
250                /// Mutator pass that replaces concrete instantiations of generic types with actual struct declarations, scoped appropriately
251                class GenericInstantiator : public DeclMutator {
252                        /// Map of (generic type, parameter list) pairs to concrete type instantiations
253                        InstantiationMap< AggregateDecl, AggregateDecl > instantiations;
254                        /// Namer for concrete types
255                        UniqueName typeNamer;
256
257                public:
258                        GenericInstantiator() : DeclMutator(), instantiations(), typeNamer("_conc_") {}
259
260                        virtual Type* mutate( StructInstType *inst );
261                        virtual Type* mutate( UnionInstType *inst );
262
263        //              virtual Expression* mutate( MemberExpr *memberExpr );
264
265                        virtual void doBeginScope();
266                        virtual void doEndScope();
267                private:
268                        /// Wrap instantiation lookup for structs
269                        StructDecl* lookup( StructInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (StructDecl*)instantiations.lookup( inst->get_baseStruct(), typeSubs ); }
270                        /// Wrap instantiation lookup for unions
271                        UnionDecl* lookup( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs ) { return (UnionDecl*)instantiations.lookup( inst->get_baseUnion(), typeSubs ); }
272                        /// Wrap instantiation insertion for structs
273                        void insert( StructInstType *inst, const std::list< TypeExpr* > &typeSubs, StructDecl *decl ) { instantiations.insert( inst->get_baseStruct(), typeSubs, decl ); }
274                        /// Wrap instantiation insertion for unions
275                        void insert( UnionInstType *inst, const std::list< TypeExpr* > &typeSubs, UnionDecl *decl ) { instantiations.insert( inst->get_baseUnion(), typeSubs, decl ); }
276                };
277
278                /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
279                /// also fixes offsetof expressions.
280                class MemberExprFixer : public PolyMutator {
281                  public:
282                        template< typename DeclClass >
283                        DeclClass *handleDecl( DeclClass *decl, Type *type );
284                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
285                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
286                        virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
287                        virtual TypeDecl *mutate( TypeDecl *objectDecl );
288                        virtual Statement *mutate( DeclStmt *declStmt );
289                        virtual Type *mutate( PointerType *pointerType );
290                        virtual Type *mutate( FunctionType *funcType );
291                        virtual Expression *mutate( MemberExpr *memberExpr );
292                        virtual Expression *mutate( OffsetofExpr *offsetofExpr );
293                };
294
295                /// 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
296                class Pass3 : public PolyMutator {
297                  public:
298                        template< typename DeclClass >
299                        DeclClass *handleDecl( DeclClass *decl, Type *type );
300                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
301                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
302                        virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
303                        virtual TypeDecl *mutate( TypeDecl *objectDecl );
304                        virtual Type *mutate( PointerType *pointerType );
305                        virtual Type *mutate( FunctionType *funcType );
306                  private:
307                };
308
309        } // anonymous namespace
310
311        /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
312        template< typename MutatorType >
313        inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
314                bool seenIntrinsic = false;
315                SemanticError errors;
316                for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
317                        try {
318                                if ( *i ) {
319                                        if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
320                                                seenIntrinsic = true;
321                                        } else if ( seenIntrinsic ) {
322                                                seenIntrinsic = false; // break on this line when debugging for end of prelude
323                                        }
324
325                                        *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
326                                        assert( *i );
327                                } // if
328                        } catch( SemanticError &e ) {
329                                errors.append( e );
330                        } // try
331                } // for
332                if ( ! errors.isEmpty() ) {
333                        throw errors;
334                } // if
335        }
336
337        void box( std::list< Declaration *>& translationUnit ) {
338                LayoutFunctionBuilder layoutBuilder;
339                Pass1 pass1;
340                Pass2 pass2;
341                GenericInstantiator instantiator;
342                MemberExprFixer memberFixer;
343                Pass3 pass3;
344               
345                layoutBuilder.mutateDeclarationList( translationUnit );
346                mutateTranslationUnit/*All*/( translationUnit, pass1 );
347                mutateTranslationUnit/*All*/( translationUnit, pass2 );
348                instantiator.mutateDeclarationList( translationUnit );
349                mutateTranslationUnit/*All*/( translationUnit, memberFixer );
350                mutateTranslationUnit/*All*/( translationUnit, pass3 );
351        }
352
353        ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
354
355        DeclarationWithType *LayoutFunctionBuilder::mutate( FunctionDecl *functionDecl ) {
356                functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
357                mutateAll( functionDecl->get_oldDecls(), *this );
358                ++functionNesting;
359                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
360                --functionNesting;
361                return functionDecl;
362        }
363       
364        /// Get a list of type declarations that will affect a layout function
365        std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
366                std::list< TypeDecl * > otypeDecls;
367
368                for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
369                        if ( (*decl)->get_kind() == TypeDecl::Any ) {
370                                otypeDecls.push_back( *decl );
371                        }
372                }
373               
374                return otypeDecls;
375        }
376
377        /// Adds parameters for otype layout to a function type
378        void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
379                BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
380               
381                for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
382                        TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
383                        layoutFnType->get_parameters().push_back( new ObjectDecl( sizeofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
384                        layoutFnType->get_parameters().push_back( new ObjectDecl( alignofName( &paramType ), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
385                }
386        }
387
388        /// Builds a layout function declaration
389        FunctionDecl *buildLayoutFunctionDecl( const std::string &typeName, unsigned int functionNesting, FunctionType *layoutFnType ) {
390                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
391                // because each unit generates copies of the default routines for each aggregate.
392                FunctionDecl *layoutDecl = new FunctionDecl(
393                        "__layoutof_" + typeName, functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, layoutFnType, new CompoundStmt( noLabels ), true, false );
394                layoutDecl->fixUniqueId();
395                return layoutDecl;
396        }
397
398        /// Makes a unary operation
399        Expression *makeOp( const std::string &name, Expression *arg ) {
400                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
401                expr->get_args().push_back( arg );
402                return expr;
403        }
404
405        /// Makes a binary operation
406        Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
407                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
408                expr->get_args().push_back( lhs );
409                expr->get_args().push_back( rhs );
410                return expr;
411        }
412
413        /// Returns the dereference of a local pointer variable
414        Expression *derefVar( ObjectDecl *var ) {
415                return makeOp( "*?", new VariableExpr( var ) );
416        }
417
418        /// makes an if-statement with a single-expression if-block and no then block
419        Statement *makeCond( Expression *cond, Expression *ifPart ) {
420                return new IfStmt( noLabels, cond, new ExprStmt( noLabels, ifPart ), 0 );
421        }
422
423        /// makes a statement that assigns rhs to lhs if lhs < rhs
424        Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
425                return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
426        }
427
428        /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
429        Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
430                // check that the lhs is zeroed out to the level of rhs
431                Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), "1" ) ) ) );
432                // if not aligned, increment to alignment
433                Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
434                return makeCond( ifCond, ifExpr );
435        }
436       
437        /// adds an expression to a compound statement
438        void addExpr( CompoundStmt *stmts, Expression *expr ) {
439                stmts->get_kids().push_back( new ExprStmt( noLabels, expr ) );
440        }
441
442        /// adds a statement to a compound statement
443        void addStmt( CompoundStmt *stmts, Statement *stmt ) {
444                stmts->get_kids().push_back( stmt );
445        }
446       
447        Declaration *LayoutFunctionBuilder::mutate( StructDecl *structDecl ) {
448                // do not generate layout function for "empty" tag structs
449                if ( structDecl->get_members().empty() ) return structDecl;
450
451                // get parameters that can change layout, exiting early if none
452                std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
453                if ( otypeParams.empty() ) return structDecl;
454
455                // build layout function signature
456                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
457                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
458                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
459               
460                ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
461                layoutFnType->get_parameters().push_back( sizeParam );
462                ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
463                layoutFnType->get_parameters().push_back( alignParam );
464                ObjectDecl *offsetParam = new ObjectDecl( "__offsetof_" + structDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
465                layoutFnType->get_parameters().push_back( offsetParam );
466                addOtypeParams( layoutFnType, otypeParams );
467
468                // build function decl
469                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl->get_name(), functionNesting, layoutFnType );
470
471                // calculate struct layout in function body
472
473                // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size
474                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "0" ) ) ) );
475                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
476                unsigned long n_members = 0;
477                bool firstMember = true;
478                for ( std::list< Declaration* >::const_iterator member = structDecl->get_members().begin(); member != structDecl->get_members().end(); ++member ) {
479                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
480                        assert( dwt );
481                        Type *memberType = dwt->get_type();
482
483                        if ( firstMember ) {
484                                firstMember = false;
485                        } else {
486                                // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
487                                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
488                        }
489                       
490                        // place current size in the current offset index
491                        addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from( n_members ) ) ),
492                                                                              derefVar( sizeParam ) ) );
493                        ++n_members;
494
495                        // add member size to current size
496                        addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
497                       
498                        // take max of member alignment and global alignment
499                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
500                }
501                // make sure the type is end-padded to a multiple of its alignment
502                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
503
504                addDeclarationAfter( layoutDecl );
505                return structDecl;
506        }
507       
508        Declaration *LayoutFunctionBuilder::mutate( UnionDecl *unionDecl ) {
509                // do not generate layout function for "empty" tag unions
510                if ( unionDecl->get_members().empty() ) return unionDecl;
511               
512                // get parameters that can change layout, exiting early if none
513                std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
514                if ( otypeParams.empty() ) return unionDecl;
515
516                // build layout function signature
517                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
518                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
519                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
520               
521                ObjectDecl *sizeParam = new ObjectDecl( "__sizeof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
522                layoutFnType->get_parameters().push_back( sizeParam );
523                ObjectDecl *alignParam = new ObjectDecl( "__alignof_" + unionDecl->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
524                layoutFnType->get_parameters().push_back( alignParam );
525                addOtypeParams( layoutFnType, otypeParams );
526
527                // build function decl
528                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl->get_name(), functionNesting, layoutFnType );
529
530                // calculate union layout in function body
531                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
532                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant( sizeAlignType->clone(), "1" ) ) ) );
533                for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
534                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
535                        assert( dwt );
536                        Type *memberType = dwt->get_type();
537                       
538                        // take max member size and global size
539                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
540                       
541                        // take max of member alignment and global alignment
542                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
543                }
544                // make sure the type is end-padded to a multiple of its alignment
545                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
546
547                addDeclarationAfter( layoutDecl );
548                return unionDecl;
549        }
550       
551        ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
552
553        namespace {
554                std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
555                        std::stringstream name;
556
557                        // NOTE: this function previously used isPolyObj, which failed to produce
558                        // the correct thing in some situations. It's not clear to me why this wasn't working.
559
560                        // if the return type or a parameter type involved polymorphic types, then the adapter will need
561                        // to take those polymorphic types as pointers. Therefore, there can be two different functions
562                        // with the same mangled name, so we need to further mangle the names.
563                        for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
564                                if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
565                                        name << "P";
566                                } else {
567                                        name << "M";
568                                }
569                        }
570                        name << "_";
571                        std::list< DeclarationWithType *> &paramList = function->get_parameters();
572                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
573                                if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
574                                        name << "P";
575                                } else {
576                                        name << "M";
577                                }
578                        } // for
579                        return name.str();
580                }
581
582                std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
583                        return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
584                }
585
586                std::string makeAdapterName( const std::string &mangleName ) {
587                        return "_adapter" + mangleName;
588                }
589
590                Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {}
591
592                /// Returns T if the given declaration is (*?=?)(T *, T) for some TypeInstType T (return not checked, but maybe should be), NULL otherwise
593                TypeInstType *isTypeInstAssignment( DeclarationWithType *decl ) {
594                        if ( decl->get_name() == "?=?" ) {
595                                if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
596                                        if ( funType->get_parameters().size() == 2 ) {
597                                                if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
598                                                        if ( TypeInstType *refType = dynamic_cast< TypeInstType *>( pointer->get_base() ) ) {
599                                                                if ( TypeInstType *refType2 = dynamic_cast< TypeInstType *>( funType->get_parameters().back()->get_type() ) ) {
600                                                                        if ( refType->get_name() == refType2->get_name() ) {
601                                                                                return refType;
602                                                                        } // if
603                                                                } // if
604                                                        } // if
605                                                } // if
606                                        } // if
607                                } // if
608                        } // if
609                        return 0;
610                }
611               
612                /// returns T if the given declaration is: (*?=?)(T *, T) for some type T (return not checked, but maybe should be), NULL otherwise
613                /// Only picks assignments where neither parameter is cv-qualified
614                Type *isAssignment( DeclarationWithType *decl ) {
615                        if ( decl->get_name() == "?=?" ) {
616                                if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
617                                        if ( funType->get_parameters().size() == 2 ) {
618                                                Type::Qualifiers defaultQualifiers;
619                                                Type *paramType1 = funType->get_parameters().front()->get_type();
620                                                if ( paramType1->get_qualifiers() != defaultQualifiers ) return 0;
621                                                Type *paramType2 = funType->get_parameters().back()->get_type();
622                                                if ( paramType2->get_qualifiers() != defaultQualifiers ) return 0;
623                                               
624                                                if ( PointerType *pointerType = dynamic_cast< PointerType* >( paramType1 ) ) {
625                                                        Type *baseType1 = pointerType->get_base();
626                                                        if ( baseType1->get_qualifiers() != defaultQualifiers ) return 0;
627                                                        SymTab::Indexer dummy;
628                                                        if ( ResolvExpr::typesCompatible( baseType1, paramType2, dummy ) ) {
629                                                                return baseType1;
630                                                        } // if
631                                                } // if
632                                        } // if
633                                } // if
634                        } // if
635                        return 0;
636                }
637
638                void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
639                        // what if a nested function uses an assignment operator?
640                        // assignOps.clear();
641                        for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
642                                for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
643                                        std::string typeName;
644                                        if ( TypeInstType *typeInst = isTypeInstAssignment( *assert ) ) {
645                                                assignOps[ typeInst->get_name() ] = *assert;
646                                        } // if
647                                } // for
648                        } // for
649                }
650
651                DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
652                        // if this is a assignment function, put it in the map for this scope
653                        if ( Type *assignedType = isAssignment( functionDecl ) ) {
654                                if ( ! dynamic_cast< TypeInstType* >( assignedType ) ) {
655                                        scopedAssignOps.insert( assignedType, functionDecl );
656                                }
657                        }
658
659                        if ( functionDecl->get_statements() ) {         // empty routine body ?
660                                doBeginScope();
661                                TyVarMap oldtyVars = scopeTyVars;
662                                std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
663                                DeclarationWithType *oldRetval = retval;
664                                bool oldUseRetval = useRetval;
665
666                                // process polymorphic return value
667                                retval = 0;
668                                if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
669                                        retval = functionDecl->get_functionType()->get_returnVals().front();
670
671                                        // give names to unnamed return values
672                                        if ( retval->get_name() == "" ) {
673                                                retval->set_name( "_retparm" );
674                                                retval->set_linkage( LinkageSpec::C );
675                                        } // if
676                                } // if
677
678                                FunctionType *functionType = functionDecl->get_functionType();
679                                makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
680                                findAssignOps( functionDecl->get_functionType()->get_forall() );
681
682                                std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
683                                std::list< FunctionType *> functions;
684                                for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
685                                        for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
686                                                findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
687                                        } // for
688                                } // for
689                                for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
690                                        findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
691                                } // for
692
693                                for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
694                                        std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
695                                        if ( adapters.find( mangleName ) == adapters.end() ) {
696                                                std::string adapterName = makeAdapterName( mangleName );
697                                                adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
698                                        } // if
699                                } // for
700
701                                functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
702
703                                scopeTyVars = oldtyVars;
704                                assignOps = oldassignOps;
705                                // std::cerr << "end FunctionDecl: ";
706                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
707                                //      std::cerr << i->first << " ";
708                                // }
709                                // std::cerr << "\n";
710                                retval = oldRetval;
711                                useRetval = oldUseRetval;
712                                doEndScope();
713                        } // if
714                        return functionDecl;
715                }
716
717                TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
718                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
719                        return Mutator::mutate( typeDecl );
720                }
721
722                Expression *Pass1::mutate( CommaExpr *commaExpr ) {
723                        bool oldUseRetval = useRetval;
724                        useRetval = false;
725                        commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
726                        useRetval = oldUseRetval;
727                        commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
728                        return commaExpr;
729                }
730
731                Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
732                        bool oldUseRetval = useRetval;
733                        useRetval = false;
734                        condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
735                        useRetval = oldUseRetval;
736                        condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
737                        condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
738                        return condExpr;
739
740                }
741
742                void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
743                        Type *polyBase = hasPolyBase( parmType, exprTyVars );
744                        if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
745                                std::string sizeName = sizeofName( polyBase );
746                                if ( seenTypes.count( sizeName ) ) return;
747
748                                arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
749                                arg++;
750                                arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
751                                arg++;
752                                if ( dynamic_cast< StructInstType* >( polyBase ) ) {
753                                        if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
754                                                // zero-length arrays are forbidden by C, so don't pass offset for empty struct
755                                                if ( ! argBaseStructType->get_baseStruct()->get_members().empty() ) {
756                                                        arg = appExpr->get_args().insert( arg, new OffsetPackExpr( argBaseStructType->clone() ) );
757                                                        arg++;
758                                                }
759                                        } else {
760                                                throw SemanticError( "Cannot pass non-struct type for generic struct" );
761                                        }
762                                }
763
764                                seenTypes.insert( sizeName );
765                        }
766                }
767
768                void Pass1::passTypeVars( ApplicationExpr *appExpr, ReferenceToType *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
769                        // pass size/align for type variables
770                        for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
771                                ResolvExpr::EqvClass eqvClass;
772                                assert( env );
773                                if ( tyParm->second == TypeDecl::Any ) {
774                                        Type *concrete = env->lookup( tyParm->first );
775                                        if ( concrete ) {
776                                                arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
777                                                arg++;
778                                                arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
779                                                arg++;
780                                        } else {
781                                                throw SemanticError( "unbound type variable in application ", appExpr );
782                                        } // if
783                                } // if
784                        } // for
785
786                        // add size/align for generic types to parameter list
787                        if ( appExpr->get_function()->get_results().empty() ) return;
788                        FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
789                        assert( funcType );
790
791                        std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
792                        std::list< Expression* >::const_iterator fnArg = arg;
793                        std::set< std::string > seenTypes; //< names for generic types we've seen
794
795                        // a polymorphic return type may need to be added to the argument list
796                        if ( polyRetType ) {
797                                Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
798                                passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
799                        }
800                       
801                        // add type information args for presently unseen types in parameter list
802                        for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
803                                VariableExpr *fnArgBase = getBaseVar( *fnArg );
804                                if ( ! fnArgBase || fnArgBase->get_results().empty() ) continue;
805                                passArgTypeVars( appExpr, (*fnParm)->get_type(), fnArgBase->get_results().front(), arg, exprTyVars, seenTypes );
806                        }
807                }
808
809                ObjectDecl *Pass1::makeTemporary( Type *type ) {
810                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
811                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
812                        return newObj;
813                }
814
815                Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
816                        // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
817                        // if ( useRetval ) {
818                        //      assert( retval );
819                        //      arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
820                        //      arg++;
821                        // } else {
822
823                        // Create temporary to hold return value of polymorphic function and produce that temporary as a result
824                        // using a comma expression.  Possibly change comma expression into statement expression "{}" for multiple
825                        // return values.
826                        ObjectDecl *newObj = makeTemporary( retType->clone() );
827                        Expression *paramExpr = new VariableExpr( newObj );
828
829                        // If the type of the temporary is not polymorphic, box temporary by taking its address;
830                        // otherwise the temporary is already boxed and can be used directly.
831                        if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
832                                paramExpr = new AddressExpr( paramExpr );
833                        } // if
834                        arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
835                        arg++;
836                        // Build a comma expression to call the function and emulate a normal return.
837                        CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
838                        commaExpr->set_env( appExpr->get_env() );
839                        appExpr->set_env( 0 );
840                        return commaExpr;
841                        // } // if
842                        // return appExpr;
843                }
844
845                void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
846                        for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
847                                TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
848                                assert(paramType && "Aggregate parameters should be type expressions");
849                                paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
850                        }
851                }
852
853                Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
854                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
855                                Type *concrete = env->lookup( typeInst->get_name() );
856                                if ( concrete == 0 ) {
857                                        throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
858                                } // if
859                                return concrete;
860                        } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
861                                if ( doClone ) {
862                                        structType = structType->clone();
863                                }
864                                replaceParametersWithConcrete( appExpr, structType->get_parameters() );
865                                return structType;
866                        } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
867                                if ( doClone ) {
868                                        unionType = unionType->clone();
869                                }
870                                replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
871                                return unionType;
872                        }
873                        return type;
874                }
875
876                Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
877                        assert( env );
878                        Type *concrete = replaceWithConcrete( appExpr, polyType );
879                        // add out-parameter for return value   
880                        return addRetParam( appExpr, function, concrete, arg );
881                }
882
883                Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
884                        Expression *ret = appExpr;
885                        if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
886                                ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
887                        } // if
888                        std::string mangleName = mangleAdapterName( function, tyVars );
889                        std::string adapterName = makeAdapterName( mangleName );
890
891                        // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
892                        Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
893                        appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
894                        appExpr->set_function( new NameExpr( adapterName ) );
895
896                        return ret;
897                }
898
899                void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
900                        assert( ! arg->get_results().empty() );
901                        if ( isPolyType( param, exprTyVars ) ) {
902                                if ( isPolyType( arg->get_results().front() ) ) {
903                                        // if the argument's type is polymorphic, we don't need to box again!
904                                        return;
905                                } else if ( arg->get_results().front()->get_isLvalue() ) {
906                                        // VariableExpr and MemberExpr are lvalues
907                                        arg = new AddressExpr( arg );
908                                } else {
909                                        // use type computed in unification to declare boxed variables
910                                        Type * newType = param->clone();
911                                        if ( env ) env->apply( newType );
912                                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
913                                        newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
914                                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
915                                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
916                                        assign->get_args().push_back( new VariableExpr( newObj ) );
917                                        assign->get_args().push_back( arg );
918                                        stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
919                                        arg = new AddressExpr( new VariableExpr( newObj ) );
920                                } // if
921                        } // if
922                }
923
924                /// cast parameters to polymorphic functions so that types are replaced with
925                /// void * if they are type parameters in the formal type.
926                /// this gets rid of warnings from gcc.
927                void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
928                        Type * newType = formal->clone();
929                        if ( getFunctionType( newType ) ) {
930                                newType = ScrubTyVars::scrub( newType, tyVars );
931                                actual = new CastExpr( actual, newType );
932                        } // if
933                }
934
935                void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
936                        for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
937                                assert( arg != appExpr->get_args().end() );
938                                addCast( *arg, (*param)->get_type(), exprTyVars );
939                                boxParam( (*param)->get_type(), *arg, exprTyVars );
940                        } // for
941                }
942
943                void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
944                        std::list< Expression *>::iterator cur = arg;
945                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
946                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
947                                        InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
948                                        assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
949                                        Expression *newExpr = inferParam->second.expr->clone();
950                                        addCast( newExpr, (*assert)->get_type(), tyVars );
951                                        boxParam( (*assert)->get_type(), newExpr, tyVars );
952                                        appExpr->get_args().insert( cur, newExpr );
953                                } // for
954                        } // for
955                }
956
957                void makeRetParm( FunctionType *funcType ) {
958                        DeclarationWithType *retParm = funcType->get_returnVals().front();
959
960                        // make a new parameter that is a pointer to the type of the old return value
961                        retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
962                        funcType->get_parameters().push_front( retParm );
963
964                        // we don't need the return value any more
965                        funcType->get_returnVals().clear();
966                }
967
968                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
969                        // actually make the adapter type
970                        FunctionType *adapter = adaptee->clone();
971                        if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
972                                makeRetParm( adapter );
973                        } // if
974                        adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
975                        return adapter;
976                }
977
978                Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
979                        assert( param );
980                        assert( arg );
981                        if ( isPolyType( realParam->get_type(), tyVars ) ) {
982                                if ( ! isPolyType( arg->get_type() ) ) {
983                                        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
984                                        deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
985                                        deref->get_results().push_back( arg->get_type()->clone() );
986                                        return deref;
987                                } // if
988                        } // if
989                        return new VariableExpr( param );
990                }
991
992                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 ) {
993                        UniqueName paramNamer( "_p" );
994                        for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
995                                if ( (*param)->get_name() == "" ) {
996                                        (*param)->set_name( paramNamer.newName() );
997                                        (*param)->set_linkage( LinkageSpec::C );
998                                } // if
999                                adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
1000                        } // for
1001                }
1002
1003
1004
1005                FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
1006                        FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
1007                        adapterType = ScrubTyVars::scrub( adapterType, tyVars );
1008                        DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
1009                        adapteeDecl->set_name( "_adaptee" );
1010                        ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
1011                        Statement *bodyStmt;
1012
1013                        std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
1014                        std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
1015                        std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
1016                        for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
1017                                assert( tyArg != realType->get_forall().end() );
1018                                std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
1019                                std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
1020                                std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
1021                                for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
1022                                        assert( assertArg != (*tyArg)->get_assertions().end() );
1023                                        adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
1024                                } // for
1025                        } // for
1026
1027                        std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
1028                        std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
1029                        std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
1030                        param++;                // skip adaptee parameter
1031                        if ( realType->get_returnVals().empty() ) {
1032                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1033                                bodyStmt = new ExprStmt( noLabels, adapteeApp );
1034                        } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
1035                                if ( (*param)->get_name() == "" ) {
1036                                        (*param)->set_name( "_ret" );
1037                                        (*param)->set_linkage( LinkageSpec::C );
1038                                } // if
1039                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
1040                                UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
1041                                deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
1042                                assign->get_args().push_back( deref );
1043                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1044                                assign->get_args().push_back( adapteeApp );
1045                                bodyStmt = new ExprStmt( noLabels, assign );
1046                        } else {
1047                                // adapter for a function that returns a monomorphic value
1048                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
1049                                bodyStmt = new ReturnStmt( noLabels, adapteeApp );
1050                        } // if
1051                        CompoundStmt *adapterBody = new CompoundStmt( noLabels );
1052                        adapterBody->get_kids().push_back( bodyStmt );
1053                        std::string adapterName = makeAdapterName( mangleName );
1054                        return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
1055                }
1056
1057                void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
1058                        // collect a list of function types passed as parameters or implicit parameters (assertions)
1059                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1060                        std::list< FunctionType *> functions;
1061                        for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
1062                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
1063                                        findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
1064                                } // for
1065                        } // for
1066                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1067                                findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
1068                        } // for
1069
1070                        // parameter function types for which an appropriate adapter has been generated.  we cannot use the types
1071                        // after applying substitutions, since two different parameter types may be unified to the same type
1072                        std::set< std::string > adaptersDone;
1073
1074                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1075                                FunctionType *originalFunction = (*funType)->clone();
1076                                FunctionType *realFunction = (*funType)->clone();
1077                                std::string mangleName = SymTab::Mangler::mangle( realFunction );
1078
1079                                // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
1080                                // pre-substitution parameter function type.
1081                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1082                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1083
1084                                        // apply substitution to type variables to figure out what the adapter's type should look like
1085                                        assert( env );
1086                                        env->apply( realFunction );
1087                                        mangleName = SymTab::Mangler::mangle( realFunction );
1088                                        mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
1089
1090                                        typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
1091                                        AdapterIter adapter = adapters.find( mangleName );
1092                                        if ( adapter == adapters.end() ) {
1093                                                // adapter has not been created yet in the current scope, so define it
1094                                                FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
1095                                                std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
1096                                                adapter = answer.first;
1097                                                stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
1098                                        } // if
1099                                        assert( adapter != adapters.end() );
1100
1101                                        // add the appropriate adapter as a parameter
1102                                        appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
1103                                } // if
1104                        } // for
1105                } // passAdapters
1106
1107                Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
1108                        NameExpr *opExpr;
1109                        if ( isIncr ) {
1110                                opExpr = new NameExpr( "?+=?" );
1111                        } else {
1112                                opExpr = new NameExpr( "?-=?" );
1113                        } // if
1114                        UntypedExpr *addAssign = new UntypedExpr( opExpr );
1115                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1116                                addAssign->get_args().push_back( address->get_arg() );
1117                        } else {
1118                                addAssign->get_args().push_back( appExpr->get_args().front() );
1119                        } // if
1120                        addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
1121                        addAssign->get_results().front() = appExpr->get_results().front()->clone();
1122                        if ( appExpr->get_env() ) {
1123                                addAssign->set_env( appExpr->get_env() );
1124                                appExpr->set_env( 0 );
1125                        } // if
1126                        appExpr->get_args().clear();
1127                        delete appExpr;
1128                        return addAssign;
1129                }
1130
1131                Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
1132                        if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
1133                                if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
1134                                        if ( varExpr->get_var()->get_name() == "?[?]" ) {
1135                                                assert( ! appExpr->get_results().empty() );
1136                                                assert( appExpr->get_args().size() == 2 );
1137                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1138                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1139                                                assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1140                                                UntypedExpr *ret = 0;
1141                                                if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1142                                                        ret = new UntypedExpr( new NameExpr( "?+?" ) );
1143                                                } // if
1144                                                if ( baseType1 ) {
1145                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1146                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1147                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1148                                                        ret->get_args().push_back( appExpr->get_args().front() );
1149                                                        ret->get_args().push_back( multiply );
1150                                                } else if ( baseType2 ) {
1151                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1152                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1153                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1154                                                        ret->get_args().push_back( multiply );
1155                                                        ret->get_args().push_back( appExpr->get_args().back() );
1156                                                } // if
1157                                                if ( baseType1 || baseType2 ) {
1158                                                        ret->get_results().push_front( appExpr->get_results().front()->clone() );
1159                                                        if ( appExpr->get_env() ) {
1160                                                                ret->set_env( appExpr->get_env() );
1161                                                                appExpr->set_env( 0 );
1162                                                        } // if
1163                                                        appExpr->get_args().clear();
1164                                                        delete appExpr;
1165                                                        return ret;
1166                                                } // if
1167                                        } else if ( varExpr->get_var()->get_name() == "*?" ) {
1168                                                assert( ! appExpr->get_results().empty() );
1169                                                assert( ! appExpr->get_args().empty() );
1170                                                if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
1171                                                        Expression *ret = appExpr->get_args().front();
1172                                                        delete ret->get_results().front();
1173                                                        ret->get_results().front() = appExpr->get_results().front()->clone();
1174                                                        if ( appExpr->get_env() ) {
1175                                                                ret->set_env( appExpr->get_env() );
1176                                                                appExpr->set_env( 0 );
1177                                                        } // if
1178                                                        appExpr->get_args().clear();
1179                                                        delete appExpr;
1180                                                        return ret;
1181                                                } // if
1182                                        } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1183                                                assert( ! appExpr->get_results().empty() );
1184                                                assert( appExpr->get_args().size() == 1 );
1185                                                if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1186                                                        Type *tempType = appExpr->get_results().front()->clone();
1187                                                        if ( env ) {
1188                                                                env->apply( tempType );
1189                                                        } // if
1190                                                        ObjectDecl *newObj = makeTemporary( tempType );
1191                                                        VariableExpr *tempExpr = new VariableExpr( newObj );
1192                                                        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1193                                                        assignExpr->get_args().push_back( tempExpr->clone() );
1194                                                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1195                                                                assignExpr->get_args().push_back( address->get_arg()->clone() );
1196                                                        } else {
1197                                                                assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1198                                                        } // if
1199                                                        CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1200                                                        return new CommaExpr( firstComma, tempExpr );
1201                                                } // if
1202                                        } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1203                                                assert( ! appExpr->get_results().empty() );
1204                                                assert( appExpr->get_args().size() == 1 );
1205                                                if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
1206                                                        return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1207                                                } // if
1208                                        } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1209                                                assert( ! appExpr->get_results().empty() );
1210                                                assert( appExpr->get_args().size() == 2 );
1211                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
1212                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
1213                                                if ( baseType1 && baseType2 ) {
1214                                                        UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1215                                                        divide->get_args().push_back( appExpr );
1216                                                        divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1217                                                        divide->get_results().push_front( appExpr->get_results().front()->clone() );
1218                                                        if ( appExpr->get_env() ) {
1219                                                                divide->set_env( appExpr->get_env() );
1220                                                                appExpr->set_env( 0 );
1221                                                        } // if
1222                                                        return divide;
1223                                                } else if ( baseType1 ) {
1224                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1225                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1226                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
1227                                                        appExpr->get_args().back() = multiply;
1228                                                } else if ( baseType2 ) {
1229                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1230                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1231                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
1232                                                        appExpr->get_args().front() = multiply;
1233                                                } // if
1234                                        } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1235                                                assert( ! appExpr->get_results().empty() );
1236                                                assert( appExpr->get_args().size() == 2 );
1237                                                Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
1238                                                if ( baseType ) {
1239                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1240                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1241                                                        multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
1242                                                        appExpr->get_args().back() = multiply;
1243                                                } // if
1244                                        } // if
1245                                        return appExpr;
1246                                } // if
1247                        } // if
1248                        return 0;
1249                }
1250
1251                Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
1252                        // std::cerr << "mutate appExpr: ";
1253                        // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1254                        //      std::cerr << i->first << " ";
1255                        // }
1256                        // std::cerr << "\n";
1257                        bool oldUseRetval = useRetval;
1258                        useRetval = false;
1259                        appExpr->get_function()->acceptMutator( *this );
1260                        mutateAll( appExpr->get_args(), *this );
1261                        useRetval = oldUseRetval;
1262
1263                        assert( ! appExpr->get_function()->get_results().empty() );
1264                        PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1265                        assert( pointer );
1266                        FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1267                        assert( function );
1268
1269                        if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1270                                return newExpr;
1271                        } // if
1272
1273                        Expression *ret = appExpr;
1274
1275                        std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1276                        std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1277
1278                        TyVarMap exprTyVars;
1279                        makeTyVarMap( function, exprTyVars );
1280                        ReferenceToType *polyRetType = isPolyRet( function );
1281
1282                        if ( polyRetType ) {
1283                                ret = addPolyRetParam( appExpr, function, polyRetType, arg );
1284                        } else if ( needsAdapter( function, scopeTyVars ) ) {
1285                                // std::cerr << "needs adapter: ";
1286                                // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1287                                //      std::cerr << i->first << " ";
1288                                // }
1289                                // std::cerr << "\n";
1290                                // change the application so it calls the adapter rather than the passed function
1291                                ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1292                        } // if
1293                        arg = appExpr->get_args().begin();
1294
1295                        passTypeVars( appExpr, polyRetType, arg, exprTyVars );
1296                        addInferredParams( appExpr, function, arg, exprTyVars );
1297
1298                        arg = paramBegin;
1299
1300                        boxParams( appExpr, function, arg, exprTyVars );
1301
1302                        passAdapters( appExpr, function, exprTyVars );
1303
1304                        return ret;
1305                }
1306
1307                Expression *Pass1::mutate( UntypedExpr *expr ) {
1308                        if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1309                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1310                                        if ( name->get_name() == "*?" ) {
1311                                                Expression *ret = expr->get_args().front();
1312                                                expr->get_args().clear();
1313                                                delete expr;
1314                                                return ret->acceptMutator( *this );
1315                                        } // if
1316                                } // if
1317                        } // if
1318                        return PolyMutator::mutate( expr );
1319                }
1320
1321                Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1322                        assert( ! addrExpr->get_arg()->get_results().empty() );
1323
1324                        bool needs = false;
1325                        if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1326                                if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1327                                        if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1328                                                if ( name->get_name() == "*?" ) {
1329                                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1330                                                                assert( ! appExpr->get_function()->get_results().empty() );
1331                                                                PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1332                                                                assert( pointer );
1333                                                                FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1334                                                                assert( function );
1335                                                                needs = needsAdapter( function, scopeTyVars );
1336                                                        } // if
1337                                                } // if
1338                                        } // if
1339                                } // if
1340                        } // if
1341                        addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1342                        if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
1343                                Expression *ret = addrExpr->get_arg();
1344                                delete ret->get_results().front();
1345                                ret->get_results().front() = addrExpr->get_results().front()->clone();
1346                                addrExpr->set_arg( 0 );
1347                                delete addrExpr;
1348                                return ret;
1349                        } else {
1350                                return addrExpr;
1351                        } // if
1352                }
1353
1354                /// Wraps a function declaration in a new pointer-to-function variable expression
1355                VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1356                        // line below cloned from FixFunction.cc
1357                        ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1358                                                                  new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1359                        functionObj->set_mangleName( functionDecl->get_mangleName() );
1360                        return new VariableExpr( functionObj );
1361                }
1362               
1363                Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1364                        if ( retval && returnStmt->get_expr() ) {
1365                                assert( ! returnStmt->get_expr()->get_results().empty() );
1366                                // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1367                                // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1368                                // by this point, a cast expr on a polymorphic return value is redundant
1369                                while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1370                                        returnStmt->set_expr( castExpr->get_arg() );
1371                                        returnStmt->get_expr()->set_env( castExpr->get_env() );
1372                                        castExpr->set_env( 0 );
1373                                        castExpr->set_arg( 0 );
1374                                        delete castExpr;
1375                                } //while
1376
1377                                // find assignment operator for (polymorphic) return type
1378                                ApplicationExpr *assignExpr = 0;
1379                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1380                                        // find assignment operator for type variable
1381                                        std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1382                                        if ( assignIter == assignOps.end() ) {
1383                                                throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1384                                        } // if
1385                                        assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1386                                } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1387                                        // find assignment operator for generic type
1388                                        DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1389                                        if ( ! functionDecl ) {
1390                                                throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1391                                        }
1392
1393                                        // wrap it up in an application expression
1394                                        assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1395                                        assignExpr->set_env( env->clone() );
1396
1397                                        // find each of its needed secondary assignment operators
1398                                        std::list< Expression* > &tyParams = refType->get_parameters();
1399                                        std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1400                                        std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1401                                        std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1402                                        for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1403                                                // Add appropriate mapping to assignment expression environment
1404                                                TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1405                                                assert( formalTypeExpr && "type parameters must be type expressions" );
1406                                                Type *formalType = formalTypeExpr->get_type();
1407                                                assignExpr->get_env()->add( (*forallIt)->get_name(), formalType );
1408
1409                                                // skip types with no assign op (ftype/dtype)
1410                                                if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue;
1411
1412                                                // find assignment operator for formal type
1413                                                DeclarationWithType *assertAssign = 0;
1414                                                if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1415                                                        std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1416                                                        if ( assertAssignIt == assignOps.end() ) {
1417                                                                throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1418                                                        }
1419                                                        assertAssign = assertAssignIt->second;
1420                                                } else {
1421                                                        assertAssign = scopedAssignOps.find( formalType );
1422                                                        if ( ! assertAssign ) {
1423                                                                throw SemanticError( "No assignment operation found for ", formalType );
1424                                                        }
1425                                                }
1426
1427                                                // add inferred parameter for field assignment operator to assignment expression
1428                                                std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1429                                                assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1430                                                DeclarationWithType *actualDecl = asserts.front();
1431                                                assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1432                                                        = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1433                                        }
1434                                }
1435                                assert( assignExpr );
1436
1437                                // replace return statement with appropriate assignment to out parameter
1438                                Expression *retParm = new NameExpr( retval->get_name() );
1439                                retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1440                                assignExpr->get_args().push_back( retParm );
1441                                assignExpr->get_args().push_back( returnStmt->get_expr() );
1442                                stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1443                                // } else {
1444                                //      useRetval = true;
1445                                //      stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1446                                //      useRetval = false;
1447                                // } // if
1448                                returnStmt->set_expr( 0 );
1449                        } else {
1450                                returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1451                        } // if
1452                        return returnStmt;
1453                }
1454
1455                Type * Pass1::mutate( PointerType *pointerType ) {
1456                        TyVarMap oldtyVars = scopeTyVars;
1457                        makeTyVarMap( pointerType, scopeTyVars );
1458
1459                        Type *ret = Mutator::mutate( pointerType );
1460
1461                        scopeTyVars = oldtyVars;
1462                        return ret;
1463                }
1464
1465                Type * Pass1::mutate( FunctionType *functionType ) {
1466                        TyVarMap oldtyVars = scopeTyVars;
1467                        makeTyVarMap( functionType, scopeTyVars );
1468
1469                        Type *ret = Mutator::mutate( functionType );
1470
1471                        scopeTyVars = oldtyVars;
1472                        return ret;
1473                }
1474
1475                void Pass1::doBeginScope() {
1476                        adapters.beginScope();
1477                        scopedAssignOps.beginScope();
1478                }
1479
1480                void Pass1::doEndScope() {
1481                        adapters.endScope();
1482                        scopedAssignOps.endScope();
1483                }
1484
1485////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1486
1487                void Pass2::addAdapters( FunctionType *functionType ) {
1488                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1489                        std::list< FunctionType *> functions;
1490                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1491                                Type *orig = (*arg)->get_type();
1492                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1493                                (*arg)->set_type( orig );
1494                        }
1495                        std::set< std::string > adaptersDone;
1496                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1497                                std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1498                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1499                                        std::string adapterName = makeAdapterName( mangleName );
1500                                        paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1501                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1502                                }
1503                        }
1504//  deleteAll( functions );
1505                }
1506
1507                template< typename DeclClass >
1508                DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1509                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1510
1511                        return ret;
1512                }
1513
1514                DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1515                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1516                }
1517
1518                ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1519                        return handleDecl( objectDecl, objectDecl->get_type() );
1520                }
1521
1522                TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1523                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1524                        if ( typeDecl->get_base() ) {
1525                                return handleDecl( typeDecl, typeDecl->get_base() );
1526                        } else {
1527                                return Mutator::mutate( typeDecl );
1528                        }
1529                }
1530
1531                TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1532                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1533                }
1534
1535                Type * Pass2::mutate( PointerType *pointerType ) {
1536                        TyVarMap oldtyVars = scopeTyVars;
1537                        makeTyVarMap( pointerType, scopeTyVars );
1538
1539                        Type *ret = Mutator::mutate( pointerType );
1540
1541                        scopeTyVars = oldtyVars;
1542                        return ret;
1543                }
1544
1545                Type *Pass2::mutate( FunctionType *funcType ) {
1546                        TyVarMap oldtyVars = scopeTyVars;
1547                        makeTyVarMap( funcType, scopeTyVars );
1548
1549                        // move polymorphic return type to parameter list
1550                        if ( isPolyRet( funcType ) ) {
1551                                DeclarationWithType *ret = funcType->get_returnVals().front();
1552                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1553                                funcType->get_parameters().push_front( ret );
1554                                funcType->get_returnVals().pop_front();
1555                        }
1556
1557                        // add size/align and assertions for type parameters to parameter list
1558                        std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1559                        std::list< DeclarationWithType *> inferredParams;
1560                        ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1561                        ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1562                                           new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1563                        for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1564                                ObjectDecl *sizeParm, *alignParm;
1565                                // add all size and alignment parameters to parameter list
1566                                if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1567                                        TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1568
1569                                        sizeParm = newObj.clone();
1570                                        sizeParm->set_name( sizeofName( &parmType ) );
1571                                        last = funcType->get_parameters().insert( last, sizeParm );
1572                                        ++last;
1573
1574                                        alignParm = newObj.clone();
1575                                        alignParm->set_name( alignofName( &parmType ) );
1576                                        last = funcType->get_parameters().insert( last, alignParm );
1577                                        ++last;
1578                                }
1579                                // move all assertions into parameter list
1580                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1581//      *assert = (*assert)->acceptMutator( *this );
1582                                        inferredParams.push_back( *assert );
1583                                }
1584                                (*tyParm)->get_assertions().clear();
1585                        }
1586
1587                        // add size/align for generic parameter types to parameter list
1588                        std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1589                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1590                                Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1591                                if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1592                                        std::string sizeName = sizeofName( polyBase );
1593                                        if ( seenTypes.count( sizeName ) ) continue;
1594
1595                                        ObjectDecl *sizeParm, *alignParm, *offsetParm;
1596                                        sizeParm = newObj.clone();
1597                                        sizeParm->set_name( sizeName );
1598                                        last = funcType->get_parameters().insert( last, sizeParm );
1599                                        ++last;
1600
1601                                        alignParm = newObj.clone();
1602                                        alignParm->set_name( alignofName( polyBase ) );
1603                                        last = funcType->get_parameters().insert( last, alignParm );
1604                                        ++last;
1605
1606                                        if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyBase ) ) {
1607                                                // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1608                                                if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1609                                                        offsetParm = newPtr.clone();
1610                                                        offsetParm->set_name( offsetofName( polyBase ) );
1611                                                        last = funcType->get_parameters().insert( last, offsetParm );
1612                                                        ++last;
1613                                                }
1614                                        }
1615
1616                                        seenTypes.insert( sizeName );
1617                                        knownLayouts.insert( sizeName );  // make sure that any type information passed into the function is accounted for
1618                                }
1619                        }
1620
1621                        // splice assertion parameters into parameter list
1622                        funcType->get_parameters().splice( last, inferredParams );
1623                        addAdapters( funcType );
1624                        mutateAll( funcType->get_returnVals(), *this );
1625                        mutateAll( funcType->get_parameters(), *this );
1626
1627                        scopeTyVars = oldtyVars;
1628                        return funcType;
1629                }
1630
1631                ObjectDecl *Pass2::makeVar( const std::string &name, Type *type, Initializer *init ) {
1632                        ObjectDecl *newObj = new ObjectDecl( name, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, init );
1633                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
1634                        return newObj;
1635                }
1636
1637                void Pass2::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1638                        for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1639                                if ( findGeneric( *param ) ) {
1640                                        // push size/align vars for a generic parameter back
1641                                        layoutCall->get_args().push_back( new NameExpr( sizeofName( *param ) ) );
1642                                        layoutCall->get_args().push_back( new NameExpr( alignofName( *param ) ) );
1643                                } else {
1644                                        layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1645                                        layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1646                                }
1647                        }
1648                }
1649
1650                /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
1651                bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
1652                        bool hasDynamicLayout = false;
1653
1654                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1655                        std::list< Expression* >::const_iterator typeParam = typeParams.begin();
1656                        for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
1657                                // skip non-otype parameters
1658                                if ( (*baseParam)->get_kind() != TypeDecl::Any ) continue;
1659                                TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
1660                                assert( typeExpr && "all otype parameters should be type expressions" );
1661
1662                                Type *type = typeExpr->get_type();
1663                                out.push_back( type );
1664                                if ( isPolyType( type ) ) hasDynamicLayout = true;
1665                        }
1666                        assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
1667
1668                        return hasDynamicLayout;
1669                }
1670               
1671                bool Pass2::findGeneric( Type *ty ) {
1672                        if ( dynamic_cast< TypeInstType* >( ty ) ) {
1673                                // NOTE this assumes that all type variables will be properly bound, and thus have their layouts in scope
1674                                return true;
1675                        } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
1676                                // check if this type already has a layout generated for it
1677                                std::string sizeName = sizeofName( ty );
1678                                if ( knownLayouts.find( sizeName ) != knownLayouts.end() ) return true;
1679                               
1680                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1681                                std::list< Type* > otypeParams;
1682                                if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
1683
1684                                // insert local variables for layout and generate call to layout function
1685                                knownLayouts.insert( sizeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1686                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1687
1688                                int n_members = structTy->get_baseStruct()->get_members().size();
1689                                if ( n_members == 0 ) {
1690                                        // all empty structs have the same layout - size 1, align 1
1691                                        makeVar( sizeName, layoutType, new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
1692                                        makeVar( alignofName( ty ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
1693                                        // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
1694                                } else {
1695                                        ObjectDecl *sizeVar = makeVar( sizeName, layoutType );
1696                                        ObjectDecl *alignVar = makeVar( alignofName( ty ), layoutType->clone() );
1697                                        ObjectDecl *offsetVar = makeVar( offsetofName( ty ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from( n_members ) ), false, false ) );
1698
1699                                        // generate call to layout function
1700                                        UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( "__layoutof_" + structTy->get_baseStruct()->get_name() ) );
1701                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1702                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1703                                        layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
1704                                        addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1705
1706                                        stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1707                                }
1708                               
1709                                return true;
1710                        } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
1711                                // check if this type already has a layout generated for it
1712                                std::string sizeName = sizeofName( ty );
1713                                if ( knownLayouts.find( sizeName ) != knownLayouts.end() ) return true;
1714                               
1715                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1716                                std::list< Type* > otypeParams;
1717                                if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
1718
1719                                // insert local variables for layout and generate call to layout function
1720                                knownLayouts.insert( sizeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1721                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1722
1723                                ObjectDecl *sizeVar = makeVar( sizeName, layoutType );
1724                                ObjectDecl *alignVar = makeVar( alignofName( ty ), layoutType->clone() );
1725                               
1726                                // generate call to layout function
1727                                UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( "__layoutof_" + unionTy->get_baseUnion()->get_name() ) );
1728                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1729                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1730                                addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1731
1732                                stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
1733
1734                                return true;
1735                        }
1736                       
1737                        return false;
1738                }
1739               
1740                Expression *Pass2::mutate( SizeofExpr *sizeofExpr ) {
1741                        Type *ty = sizeofExpr->get_type();
1742                        if ( findGeneric( ty ) ) {
1743                                Expression *ret = new NameExpr( sizeofName( ty ) );
1744                                delete sizeofExpr;
1745                                return ret;
1746                        }
1747                        return sizeofExpr;
1748                }
1749
1750                Expression *Pass2::mutate( AlignofExpr *alignofExpr ) {
1751                        Type *ty = alignofExpr->get_type();
1752                        if ( findGeneric( ty ) ) {
1753                                Expression *ret = new NameExpr( alignofName( ty ) );
1754                                delete alignofExpr;
1755                                return ret;
1756                        }
1757                        return alignofExpr;
1758                }
1759
1760                Expression *Pass2::mutate( OffsetofExpr *offsetofExpr ) {
1761                        findGeneric( offsetofExpr->get_type() );
1762                        return offsetofExpr;
1763                }
1764
1765                Expression *Pass2::mutate( OffsetPackExpr *offsetPackExpr ) {
1766                        StructInstType *ty = offsetPackExpr->get_type();
1767
1768                        Expression *ret = 0;
1769                        if ( findGeneric( ty ) ) {
1770                                // pull offset back from generated type information
1771                                ret = new NameExpr( offsetofName( ty ) );
1772                        } else {
1773                                std::string offsetName = offsetofName( ty );
1774                                if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
1775                                        // use the already-generated offsets for this type
1776                                        ret = new NameExpr( offsetName );
1777                                } else {
1778                                        std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
1779                                        Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1780
1781                                        // build initializer list for offset array
1782                                        std::list< Initializer* > inits;
1783                                        for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
1784                                                DeclarationWithType *memberDecl;
1785                                                if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
1786                                                        memberDecl = origMember->clone();
1787                                                } else {
1788                                                        memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
1789                                                }
1790                                                inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
1791                                        }
1792
1793                                        // build the offset array and replace the pack with a reference to it
1794                                        ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from( baseMembers.size() ) ), false, false ),
1795                                                        new ListInit( inits ) );
1796                                        ret = new VariableExpr( offsetArray );
1797                                }
1798                        }
1799
1800                        delete offsetPackExpr;
1801                        return ret;
1802                }
1803
1804                void Pass2::doBeginScope() {
1805                        knownLayouts.beginScope();
1806                        knownOffsets.beginScope();
1807                }
1808               
1809                void Pass2::doEndScope() {
1810                        knownLayouts.endScope();
1811                        knownOffsets.beginScope();
1812                }
1813
1814//////////////////////////////////////// GenericInstantiator //////////////////////////////////////////////////
1815
1816                /// Makes substitutions of params into baseParams; returns true if all parameters substituted for a concrete type
1817                bool makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
1818                        bool allConcrete = true;  // will finish the substitution list even if they're not all concrete
1819
1820                        // substitute concrete types for given parameters, and incomplete types for placeholders
1821                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1822                        std::list< Expression* >::const_iterator param = params.begin();
1823                        for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
1824        //                      switch ( (*baseParam)->get_kind() ) {
1825        //                      case TypeDecl::Any: {   // any type is a valid substitution here; complete types can be used to instantiate generics
1826                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
1827                                        assert(paramType && "Aggregate parameters should be type expressions");
1828                                        out.push_back( paramType->clone() );
1829                                        // check that the substituted type isn't a type variable itself
1830                                        if ( dynamic_cast< TypeInstType* >( paramType->get_type() ) ) {
1831                                                allConcrete = false;
1832                                        }
1833        //                              break;
1834        //                      }
1835        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1836        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1837        //                              break;
1838        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1839        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1840        //                              break;
1841        //                      }
1842                        }
1843
1844                        // if any parameters left over, not done
1845                        if ( baseParam != baseParams.end() ) return false;
1846        //              // if not enough parameters given, substitute remaining incomplete types for placeholders
1847        //              for ( ; baseParam != baseParams.end(); ++baseParam ) {
1848        //                      switch ( (*baseParam)->get_kind() ) {
1849        //                      case TypeDecl::Any:    // no more substitutions here, fail early
1850        //                              return false;
1851        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1852        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1853        //                              break;
1854        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1855        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1856        //                              break;
1857        //                      }
1858        //              }
1859
1860                        return allConcrete;
1861                }
1862
1863                /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
1864                void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
1865                                                                std::list< Declaration* >& out ) {
1866                        // substitute types into new members
1867                        TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
1868                        for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
1869                                Declaration *newMember = (*member)->clone();
1870                                subs.apply(newMember);
1871                                out.push_back( newMember );
1872                        }
1873                }
1874
1875                Type* GenericInstantiator::mutate( StructInstType *inst ) {
1876                        // mutate subtypes
1877                        Type *mutated = Mutator::mutate( inst );
1878                        inst = dynamic_cast< StructInstType* >( mutated );
1879                        if ( ! inst ) return mutated;
1880
1881                        // exit early if no need for further mutation
1882                        if ( inst->get_parameters().empty() ) return inst;
1883                        assert( inst->get_baseParameters() && "Base struct has parameters" );
1884
1885                        // check if type can be concretely instantiated; put substitutions into typeSubs
1886                        std::list< TypeExpr* > typeSubs;
1887                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1888                                deleteAll( typeSubs );
1889                                return inst;
1890                        }
1891
1892                        // make concrete instantiation of generic type
1893                        StructDecl *concDecl = lookup( inst, typeSubs );
1894                        if ( ! concDecl ) {
1895                                // set concDecl to new type, insert type declaration into statements to add
1896                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
1897                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs,        concDecl->get_members() );
1898                                DeclMutator::addDeclaration( concDecl );
1899                                insert( inst, typeSubs, concDecl );
1900                        }
1901                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
1902                        newInst->set_baseStruct( concDecl );
1903
1904                        deleteAll( typeSubs );
1905                        delete inst;
1906                        return newInst;
1907                }
1908
1909                Type* GenericInstantiator::mutate( UnionInstType *inst ) {
1910                        // mutate subtypes
1911                        Type *mutated = Mutator::mutate( inst );
1912                        inst = dynamic_cast< UnionInstType* >( mutated );
1913                        if ( ! inst ) return mutated;
1914
1915                        // exit early if no need for further mutation
1916                        if ( inst->get_parameters().empty() ) return inst;
1917                        assert( inst->get_baseParameters() && "Base union has parameters" );
1918
1919                        // check if type can be concretely instantiated; put substitutions into typeSubs
1920                        std::list< TypeExpr* > typeSubs;
1921                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1922                                deleteAll( typeSubs );
1923                                return inst;
1924                        }
1925
1926                        // make concrete instantiation of generic type
1927                        UnionDecl *concDecl = lookup( inst, typeSubs );
1928                        if ( ! concDecl ) {
1929                                // set concDecl to new type, insert type declaration into statements to add
1930                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
1931                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
1932                                DeclMutator::addDeclaration( concDecl );
1933                                insert( inst, typeSubs, concDecl );
1934                        }
1935                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
1936                        newInst->set_baseUnion( concDecl );
1937
1938                        deleteAll( typeSubs );
1939                        delete inst;
1940                        return newInst;
1941                }
1942
1943        //      /// Gets the base struct or union declaration for a member expression; NULL if not applicable
1944        //      AggregateDecl* getMemberBaseDecl( MemberExpr *memberExpr ) {
1945        //              // get variable for member aggregate
1946        //              VariableExpr *varExpr = dynamic_cast< VariableExpr* >( memberExpr->get_aggregate() );
1947        //              if ( ! varExpr ) return NULL;
1948        //
1949        //              // get object for variable
1950        //              ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1951        //              if ( ! objectDecl ) return NULL;
1952        //
1953        //              // get base declaration from object type
1954        //              Type *objectType = objectDecl->get_type();
1955        //              StructInstType *structType = dynamic_cast< StructInstType* >( objectType );
1956        //              if ( structType ) return structType->get_baseStruct();
1957        //              UnionInstType *unionType = dynamic_cast< UnionInstType* >( objectType );
1958        //              if ( unionType ) return unionType->get_baseUnion();
1959        //
1960        //              return NULL;
1961        //      }
1962        //
1963        //      /// Finds the declaration with the given name, returning decls.end() if none such
1964        //      std::list< Declaration* >::const_iterator findDeclNamed( const std::list< Declaration* > &decls, const std::string &name ) {
1965        //              for( std::list< Declaration* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
1966        //                      if ( (*decl)->get_name() == name ) return decl;
1967        //              }
1968        //              return decls.end();
1969        //      }
1970        //
1971        //      Expression* Instantiate::mutate( MemberExpr *memberExpr ) {
1972        //              // mutate, exiting early if no longer MemberExpr
1973        //              Expression *expr = Mutator::mutate( memberExpr );
1974        //              memberExpr = dynamic_cast< MemberExpr* >( expr );
1975        //              if ( ! memberExpr ) return expr;
1976        //
1977        //              // get declaration of member and base declaration of member, exiting early if not found
1978        //              AggregateDecl *memberBase = getMemberBaseDecl( memberExpr );
1979        //              if ( ! memberBase ) return memberExpr;
1980        //              DeclarationWithType *memberDecl = memberExpr->get_member();
1981        //              std::list< Declaration* >::const_iterator baseIt = findDeclNamed( memberBase->get_members(), memberDecl->get_name() );
1982        //              if ( baseIt == memberBase->get_members().end() ) return memberExpr;
1983        //              DeclarationWithType *baseDecl = dynamic_cast< DeclarationWithType* >( *baseIt );
1984        //              if ( ! baseDecl ) return memberExpr;
1985        //
1986        //              // check if stated type of the member is not the type of the member's declaration; if so, need a cast
1987        //              // this *SHOULD* be safe, I don't think anything but the void-replacements I put in for dtypes would make it past the typechecker
1988        //              SymTab::Indexer dummy;
1989        //              if ( ResolvExpr::typesCompatible( memberDecl->get_type(), baseDecl->get_type(), dummy ) ) return memberExpr;
1990        //              else return new CastExpr( memberExpr, memberDecl->get_type() );
1991        //      }
1992
1993                void GenericInstantiator::doBeginScope() {
1994                        DeclMutator::doBeginScope();
1995                        instantiations.beginScope();
1996                }
1997
1998                void GenericInstantiator::doEndScope() {
1999                        DeclMutator::doEndScope();
2000                        instantiations.endScope();
2001                }
2002
2003////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
2004
2005                template< typename DeclClass >
2006                DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
2007                        TyVarMap oldtyVars = scopeTyVars;
2008                        makeTyVarMap( type, scopeTyVars );
2009
2010                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2011
2012                        scopeTyVars = oldtyVars;
2013                        return ret;
2014                }
2015
2016                ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
2017                        return handleDecl( objectDecl, objectDecl->get_type() );
2018                }
2019
2020                DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
2021                        return handleDecl( functionDecl, functionDecl->get_functionType() );
2022                }
2023
2024                TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
2025                        return handleDecl( typedefDecl, typedefDecl->get_base() );
2026                }
2027
2028                TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
2029                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2030                        return Mutator::mutate( typeDecl );
2031                }
2032
2033                Type * MemberExprFixer::mutate( PointerType *pointerType ) {
2034                        TyVarMap oldtyVars = scopeTyVars;
2035                        makeTyVarMap( pointerType, scopeTyVars );
2036
2037                        Type *ret = Mutator::mutate( pointerType );
2038
2039                        scopeTyVars = oldtyVars;
2040                        return ret;
2041                }
2042
2043                Type * MemberExprFixer::mutate( FunctionType *functionType ) {
2044                        TyVarMap oldtyVars = scopeTyVars;
2045                        makeTyVarMap( functionType, scopeTyVars );
2046
2047                        Type *ret = Mutator::mutate( functionType );
2048
2049                        scopeTyVars = oldtyVars;
2050                        return ret;
2051                }
2052
2053                Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
2054                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
2055                                if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
2056                                        // change initialization of a polymorphic value object
2057                                        // to allocate storage with alloca
2058                                        Type *declType = objectDecl->get_type();
2059                                        UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
2060                                        alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
2061
2062                                        delete objectDecl->get_init();
2063
2064                                        std::list<Expression*> designators;
2065                                        objectDecl->set_init( new SingleInit( alloc, designators ) );
2066                                }
2067                        }
2068                        return Mutator::mutate( declStmt );
2069                }
2070
2071                /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
2072                long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
2073                        long i = 0;
2074                        for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
2075                                if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
2076
2077                                if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
2078                                        if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
2079                                             || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
2080                                        else continue;
2081                                } else return i;
2082                        }
2083                        return -1;
2084                }
2085
2086                /// Returns an index expression into the offset array for a type
2087                Expression *makeOffsetIndex( Type *objectType, long i ) {
2088                        std::stringstream offset_namer;
2089                        offset_namer << i;
2090                        ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
2091                        UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
2092                        fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
2093                        fieldOffset->get_args().push_back( fieldIndex );
2094                        return fieldOffset;
2095                }
2096
2097                /// Returns an expression dereferenced n times
2098                Expression *makeDerefdVar( Expression *derefdVar, long n ) {
2099                        for ( int i = 1; i < n; ++i ) {
2100                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
2101                                derefExpr->get_args().push_back( derefdVar );
2102                                derefdVar = derefExpr;
2103                        }
2104                        return derefdVar;
2105                }
2106               
2107                Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
2108                        // mutate, exiting early if no longer MemberExpr
2109                        Expression *expr = Mutator::mutate( memberExpr );
2110                        memberExpr = dynamic_cast< MemberExpr* >( expr );
2111                        if ( ! memberExpr ) return expr;
2112
2113                        // get declaration for base struct, exiting early if not found
2114                        int varDepth;
2115                        VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
2116                        if ( ! varExpr ) return memberExpr;
2117                        ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
2118                        if ( ! objectDecl ) return memberExpr;
2119
2120                        // only mutate member expressions for polymorphic types
2121                        int tyDepth;
2122                        Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
2123                        if ( ! objectType ) return memberExpr;
2124
2125                        Expression *newMemberExpr = 0;
2126                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
2127                                // look up offset index
2128                                long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
2129                                if ( i == -1 ) return memberExpr;
2130
2131                                // replace member expression with pointer to base plus offset
2132                                UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
2133                                fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
2134                                fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
2135                                newMemberExpr = fieldLoc;
2136                        } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
2137                                // union members are all at offset zero, so build appropriately-dereferenced variable
2138                                newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
2139                        } else return memberExpr;
2140                        assert( newMemberExpr );
2141
2142                        Type *memberType = memberExpr->get_member()->get_type();
2143                        if ( ! isPolyType( memberType, scopeTyVars ) ) {
2144                                // Not all members of a polymorphic type are themselves of polymorphic type; in this case the member expression should be wrapped and dereferenced to form an lvalue
2145                                CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
2146                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
2147                                derefExpr->get_args().push_back( ptrCastExpr );
2148                                newMemberExpr = derefExpr;
2149                        }
2150
2151                        delete memberExpr;
2152                        return newMemberExpr;
2153                }
2154
2155                Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
2156                        // mutate, exiting early if no longer OffsetofExpr
2157                        Expression *expr = Mutator::mutate( offsetofExpr );
2158                        offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
2159                        if ( ! offsetofExpr ) return expr;
2160
2161                        // only mutate expressions for polymorphic structs/unions
2162                        Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
2163                        if ( ! ty ) return offsetofExpr;
2164
2165                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
2166                                // replace offsetof expression by index into offset array
2167                                long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
2168                                if ( i == -1 ) return offsetofExpr;
2169
2170                                Expression *offsetInd = makeOffsetIndex( ty, i );
2171                                delete offsetofExpr;
2172                                return offsetInd;
2173                        } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
2174                                // all union members are at offset zero
2175                                delete offsetofExpr;
2176                                return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
2177                        } else return offsetofExpr;
2178                }
2179
2180////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
2181
2182                template< typename DeclClass >
2183                DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
2184                        TyVarMap oldtyVars = scopeTyVars;
2185                        makeTyVarMap( type, scopeTyVars );
2186
2187                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2188                        ScrubTyVars::scrub( decl, scopeTyVars );
2189
2190                        scopeTyVars = oldtyVars;
2191                        return ret;
2192                }
2193
2194                ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
2195                        return handleDecl( objectDecl, objectDecl->get_type() );
2196                }
2197
2198                DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
2199                        return handleDecl( functionDecl, functionDecl->get_functionType() );
2200                }
2201
2202                TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
2203                        return handleDecl( typedefDecl, typedefDecl->get_base() );
2204                }
2205
2206                TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
2207//   Initializer *init = 0;
2208//   std::list< Expression *> designators;
2209//   scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2210//   if ( typeDecl->get_base() ) {
2211//     init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
2212//   }
2213//   return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
2214
2215                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2216                        return Mutator::mutate( typeDecl );
2217                }
2218
2219                Type * Pass3::mutate( PointerType *pointerType ) {
2220                        TyVarMap oldtyVars = scopeTyVars;
2221                        makeTyVarMap( pointerType, scopeTyVars );
2222
2223                        Type *ret = Mutator::mutate( pointerType );
2224
2225                        scopeTyVars = oldtyVars;
2226                        return ret;
2227                }
2228
2229                Type * Pass3::mutate( FunctionType *functionType ) {
2230                        TyVarMap oldtyVars = scopeTyVars;
2231                        makeTyVarMap( functionType, scopeTyVars );
2232
2233                        Type *ret = Mutator::mutate( functionType );
2234
2235                        scopeTyVars = oldtyVars;
2236                        return ret;
2237                }
2238        } // anonymous namespace
2239} // namespace GenPoly
2240
2241// Local Variables: //
2242// tab-width: 4 //
2243// mode: c++ //
2244// compile-command: "make install" //
2245// End: //
Note: See TracBrowser for help on using the repository browser.