source: src/GenPoly/Box.cc @ bfae637

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

Initial compiling build with TyVarMap? as ErasableScopedMap?

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