source: src/GenPoly/Box.cc @ 3849857

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

Fix modularization for generic types, so that caller is only required to pass layout for complete generic types

  • Property mode set to 100644
File size: 102.3 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                                scopeTyVars.beginScope();
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.endScope();
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 *polyType = isPolyType( parmType, exprTyVars );
744                        if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
745                                std::string typeName = mangleType( polyType );
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* >( polyType ) ) {
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                        passAdapters( appExpr, function, exprTyVars );
1304
1305                        return ret;
1306                }
1307
1308                Expression *Pass1::mutate( UntypedExpr *expr ) {
1309                        if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1310                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1311                                        if ( name->get_name() == "*?" ) {
1312                                                Expression *ret = expr->get_args().front();
1313                                                expr->get_args().clear();
1314                                                delete expr;
1315                                                return ret->acceptMutator( *this );
1316                                        } // if
1317                                } // if
1318                        } // if
1319                        return PolyMutator::mutate( expr );
1320                }
1321
1322                Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1323                        assert( ! addrExpr->get_arg()->get_results().empty() );
1324
1325                        bool needs = false;
1326                        if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1327                                if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
1328                                        if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1329                                                if ( name->get_name() == "*?" ) {
1330                                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1331                                                                assert( ! appExpr->get_function()->get_results().empty() );
1332                                                                PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
1333                                                                assert( pointer );
1334                                                                FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
1335                                                                assert( function );
1336                                                                needs = needsAdapter( function, scopeTyVars );
1337                                                        } // if
1338                                                } // if
1339                                        } // if
1340                                } // if
1341                        } // if
1342                        addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1343                        if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
1344                                Expression *ret = addrExpr->get_arg();
1345                                delete ret->get_results().front();
1346                                ret->get_results().front() = addrExpr->get_results().front()->clone();
1347                                addrExpr->set_arg( 0 );
1348                                delete addrExpr;
1349                                return ret;
1350                        } else {
1351                                return addrExpr;
1352                        } // if
1353                }
1354
1355                /// Wraps a function declaration in a new pointer-to-function variable expression
1356                VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
1357                        // line below cloned from FixFunction.cc
1358                        ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
1359                                                                  new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
1360                        functionObj->set_mangleName( functionDecl->get_mangleName() );
1361                        return new VariableExpr( functionObj );
1362                }
1363               
1364                Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1365                        if ( retval && returnStmt->get_expr() ) {
1366                                assert( ! returnStmt->get_expr()->get_results().empty() );
1367                                // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1368                                // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
1369                                // by this point, a cast expr on a polymorphic return value is redundant
1370                                while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1371                                        returnStmt->set_expr( castExpr->get_arg() );
1372                                        returnStmt->get_expr()->set_env( castExpr->get_env() );
1373                                        castExpr->set_env( 0 );
1374                                        castExpr->set_arg( 0 );
1375                                        delete castExpr;
1376                                } //while
1377
1378                                // find assignment operator for (polymorphic) return type
1379                                ApplicationExpr *assignExpr = 0;
1380                                if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
1381                                        // find assignment operator for type variable
1382                                        ScopedMap< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1383                                        if ( assignIter == assignOps.end() ) {
1384                                                throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1385                                        } // if
1386                                        assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
1387                                } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
1388                                        // find assignment operator for generic type
1389                                        DeclarationWithType *functionDecl = scopedAssignOps.find( refType );
1390                                        if ( ! functionDecl ) {
1391                                                throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1392                                        }
1393
1394                                        // wrap it up in an application expression
1395                                        assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1396                                        assignExpr->set_env( env->clone() );
1397
1398                                        // find each of its needed secondary assignment operators
1399                                        std::list< Expression* > &tyParams = refType->get_parameters();
1400                                        std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1401                                        std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1402                                        std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1403                                        for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1404                                                // Add appropriate mapping to assignment expression environment
1405                                                TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1406                                                assert( formalTypeExpr && "type parameters must be type expressions" );
1407                                                Type *formalType = formalTypeExpr->get_type();
1408                                                assignExpr->get_env()->add( (*forallIt)->get_name(), formalType );
1409
1410                                                // skip types with no assign op (ftype/dtype)
1411                                                if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue;
1412
1413                                                // find assignment operator for formal type
1414                                                DeclarationWithType *assertAssign = 0;
1415                                                if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1416                                                        ScopedMap< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1417                                                        if ( assertAssignIt == assignOps.end() ) {
1418                                                                throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1419                                                        }
1420                                                        assertAssign = assertAssignIt->second;
1421                                                } else {
1422                                                        assertAssign = scopedAssignOps.find( formalType );
1423                                                        if ( ! assertAssign ) {
1424                                                                throw SemanticError( "No assignment operation found for ", formalType );
1425                                                        }
1426                                                }
1427
1428                                                // add inferred parameter for field assignment operator to assignment expression
1429                                                std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1430                                                assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1431                                                DeclarationWithType *actualDecl = asserts.front();
1432                                                assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1433                                                        = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1434                                        }
1435                                }
1436                                assert( assignExpr );
1437
1438                                // replace return statement with appropriate assignment to out parameter
1439                                Expression *retParm = new NameExpr( retval->get_name() );
1440                                retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1441                                assignExpr->get_args().push_back( retParm );
1442                                assignExpr->get_args().push_back( returnStmt->get_expr() );
1443                                stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1444                                // } else {
1445                                //      useRetval = true;
1446                                //      stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1447                                //      useRetval = false;
1448                                // } // if
1449                                returnStmt->set_expr( 0 );
1450                        } else {
1451                                returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1452                        } // if
1453                        return returnStmt;
1454                }
1455
1456                Type * Pass1::mutate( PointerType *pointerType ) {
1457                        scopeTyVars.beginScope();
1458                        makeTyVarMap( pointerType, scopeTyVars );
1459
1460                        Type *ret = Mutator::mutate( pointerType );
1461
1462                        scopeTyVars.endScope();
1463                        return ret;
1464                }
1465
1466                Type * Pass1::mutate( FunctionType *functionType ) {
1467                        scopeTyVars.beginScope();
1468                        makeTyVarMap( functionType, scopeTyVars );
1469
1470                        Type *ret = Mutator::mutate( functionType );
1471
1472                        scopeTyVars.endScope();
1473                        return ret;
1474                }
1475
1476                void Pass1::doBeginScope() {
1477                        adapters.beginScope();
1478                        scopedAssignOps.beginScope();
1479                }
1480
1481                void Pass1::doEndScope() {
1482                        adapters.endScope();
1483                        scopedAssignOps.endScope();
1484                }
1485
1486////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1487
1488                void Pass2::addAdapters( FunctionType *functionType ) {
1489                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1490                        std::list< FunctionType *> functions;
1491                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1492                                Type *orig = (*arg)->get_type();
1493                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1494                                (*arg)->set_type( orig );
1495                        }
1496                        std::set< std::string > adaptersDone;
1497                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1498                                std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1499                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1500                                        std::string adapterName = makeAdapterName( mangleName );
1501                                        paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
1502                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1503                                }
1504                        }
1505//  deleteAll( functions );
1506                }
1507
1508                template< typename DeclClass >
1509                DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1510                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1511
1512                        return ret;
1513                }
1514
1515                DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1516                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1517                }
1518
1519                ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1520                        return handleDecl( objectDecl, objectDecl->get_type() );
1521                }
1522
1523                TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1524                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1525                        if ( typeDecl->get_base() ) {
1526                                return handleDecl( typeDecl, typeDecl->get_base() );
1527                        } else {
1528                                return Mutator::mutate( typeDecl );
1529                        }
1530                }
1531
1532                TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1533                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1534                }
1535
1536                Type * Pass2::mutate( PointerType *pointerType ) {
1537                        scopeTyVars.beginScope();
1538                        makeTyVarMap( pointerType, scopeTyVars );
1539
1540                        Type *ret = Mutator::mutate( pointerType );
1541
1542                        scopeTyVars.endScope();
1543                        return ret;
1544                }
1545
1546                Type *Pass2::mutate( FunctionType *funcType ) {
1547                        scopeTyVars.beginScope();
1548                        makeTyVarMap( funcType, scopeTyVars );
1549
1550                        // move polymorphic return type to parameter list
1551                        if ( isPolyRet( funcType ) ) {
1552                                DeclarationWithType *ret = funcType->get_returnVals().front();
1553                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1554                                funcType->get_parameters().push_front( ret );
1555                                funcType->get_returnVals().pop_front();
1556                        }
1557
1558                        // add size/align and assertions for type parameters to parameter list
1559                        std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1560                        std::list< DeclarationWithType *> inferredParams;
1561                        ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
1562                        ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1563                                           new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1564                        for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1565                                ObjectDecl *sizeParm, *alignParm;
1566                                // add all size and alignment parameters to parameter list
1567                                if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
1568                                        TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1569                                        std::string parmName = mangleType( &parmType );
1570
1571                                        sizeParm = newObj.clone();
1572                                        sizeParm->set_name( sizeofName( parmName ) );
1573                                        last = funcType->get_parameters().insert( last, sizeParm );
1574                                        ++last;
1575
1576                                        alignParm = newObj.clone();
1577                                        alignParm->set_name( alignofName( parmName ) );
1578                                        last = funcType->get_parameters().insert( last, alignParm );
1579                                        ++last;
1580                                }
1581                                // move all assertions into parameter list
1582                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1583//      *assert = (*assert)->acceptMutator( *this );
1584                                        inferredParams.push_back( *assert );
1585                                }
1586                                (*tyParm)->get_assertions().clear();
1587                        }
1588
1589                        // add size/align for generic parameter types to parameter list
1590                        std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1591                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1592                                Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1593                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1594                                        std::string typeName = mangleType( polyType );
1595                                        if ( seenTypes.count( typeName ) ) continue;
1596
1597                                        ObjectDecl *sizeParm, *alignParm, *offsetParm;
1598                                        sizeParm = newObj.clone();
1599                                        sizeParm->set_name( sizeofName( typeName ) );
1600                                        last = funcType->get_parameters().insert( last, sizeParm );
1601                                        ++last;
1602
1603                                        alignParm = newObj.clone();
1604                                        alignParm->set_name( alignofName( typeName ) );
1605                                        last = funcType->get_parameters().insert( last, alignParm );
1606                                        ++last;
1607
1608                                        if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyType ) ) {
1609                                                // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1610                                                if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1611                                                        offsetParm = newPtr.clone();
1612                                                        offsetParm->set_name( offsetofName( typeName ) );
1613                                                        last = funcType->get_parameters().insert( last, offsetParm );
1614                                                        ++last;
1615                                                }
1616                                        }
1617
1618                                        seenTypes.insert( typeName );
1619                                }
1620                        }
1621
1622                        // splice assertion parameters into parameter list
1623                        funcType->get_parameters().splice( last, inferredParams );
1624                        addAdapters( funcType );
1625                        mutateAll( funcType->get_returnVals(), *this );
1626                        mutateAll( funcType->get_parameters(), *this );
1627
1628                        scopeTyVars.endScope();
1629                        return funcType;
1630                }
1631
1632//////////////////////////////////////// GenericInstantiator //////////////////////////////////////////////////
1633
1634                /// Makes substitutions of params into baseParams; returns true if all parameters substituted for a concrete type
1635                bool makeSubstitutions( const std::list< TypeDecl* >& baseParams, const std::list< Expression* >& params, std::list< TypeExpr* >& out ) {
1636                        bool allConcrete = true;  // will finish the substitution list even if they're not all concrete
1637
1638                        // substitute concrete types for given parameters, and incomplete types for placeholders
1639                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1640                        std::list< Expression* >::const_iterator param = params.begin();
1641                        for ( ; baseParam != baseParams.end() && param != params.end(); ++baseParam, ++param ) {
1642        //                      switch ( (*baseParam)->get_kind() ) {
1643        //                      case TypeDecl::Any: {   // any type is a valid substitution here; complete types can be used to instantiate generics
1644                                        TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
1645                                        assert(paramType && "Aggregate parameters should be type expressions");
1646                                        out.push_back( paramType->clone() );
1647                                        // check that the substituted type isn't a type variable itself
1648                                        if ( dynamic_cast< TypeInstType* >( paramType->get_type() ) ) {
1649                                                allConcrete = false;
1650                                        }
1651        //                              break;
1652        //                      }
1653        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1654        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1655        //                              break;
1656        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1657        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1658        //                              break;
1659        //                      }
1660                        }
1661
1662                        // if any parameters left over, not done
1663                        if ( baseParam != baseParams.end() ) return false;
1664        //              // if not enough parameters given, substitute remaining incomplete types for placeholders
1665        //              for ( ; baseParam != baseParams.end(); ++baseParam ) {
1666        //                      switch ( (*baseParam)->get_kind() ) {
1667        //                      case TypeDecl::Any:    // no more substitutions here, fail early
1668        //                              return false;
1669        //                      case TypeDecl::Dtype:  // dtype can be consistently replaced with void [only pointers, which become void*]
1670        //                              out.push_back( new TypeExpr( new VoidType( Type::Qualifiers() ) ) );
1671        //                              break;
1672        //                      case TypeDecl::Ftype:  // pointer-to-ftype can be consistently replaced with void (*)(void) [similar to dtype]
1673        //                              out.push_back( new TypeExpr( new FunctionType( Type::Qualifiers(), false ) ) );
1674        //                              break;
1675        //                      }
1676        //              }
1677
1678                        return allConcrete;
1679                }
1680
1681                /// Substitutes types of members of in according to baseParams => typeSubs, appending the result to out
1682                void substituteMembers( const std::list< Declaration* >& in, const std::list< TypeDecl* >& baseParams, const std::list< TypeExpr* >& typeSubs,
1683                                                                std::list< Declaration* >& out ) {
1684                        // substitute types into new members
1685                        TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() );
1686                        for ( std::list< Declaration* >::const_iterator member = in.begin(); member != in.end(); ++member ) {
1687                                Declaration *newMember = (*member)->clone();
1688                                subs.apply(newMember);
1689                                out.push_back( newMember );
1690                        }
1691                }
1692
1693                Type* GenericInstantiator::mutate( StructInstType *inst ) {
1694                        // mutate subtypes
1695                        Type *mutated = Mutator::mutate( inst );
1696                        inst = dynamic_cast< StructInstType* >( mutated );
1697                        if ( ! inst ) return mutated;
1698
1699                        // exit early if no need for further mutation
1700                        if ( inst->get_parameters().empty() ) return inst;
1701                        assert( inst->get_baseParameters() && "Base struct has parameters" );
1702
1703                        // check if type can be concretely instantiated; put substitutions into typeSubs
1704                        std::list< TypeExpr* > typeSubs;
1705                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1706                                deleteAll( typeSubs );
1707                                return inst;
1708                        }
1709
1710                        // make concrete instantiation of generic type
1711                        StructDecl *concDecl = lookup( inst, typeSubs );
1712                        if ( ! concDecl ) {
1713                                // set concDecl to new type, insert type declaration into statements to add
1714                                concDecl = new StructDecl( typeNamer.newName( inst->get_name() ) );
1715                                substituteMembers( inst->get_baseStruct()->get_members(), *inst->get_baseParameters(), typeSubs,        concDecl->get_members() );
1716                                DeclMutator::addDeclaration( concDecl );
1717                                insert( inst, typeSubs, concDecl );
1718                        }
1719                        StructInstType *newInst = new StructInstType( inst->get_qualifiers(), concDecl->get_name() );
1720                        newInst->set_baseStruct( concDecl );
1721
1722                        deleteAll( typeSubs );
1723                        delete inst;
1724                        return newInst;
1725                }
1726
1727                Type* GenericInstantiator::mutate( UnionInstType *inst ) {
1728                        // mutate subtypes
1729                        Type *mutated = Mutator::mutate( inst );
1730                        inst = dynamic_cast< UnionInstType* >( mutated );
1731                        if ( ! inst ) return mutated;
1732
1733                        // exit early if no need for further mutation
1734                        if ( inst->get_parameters().empty() ) return inst;
1735                        assert( inst->get_baseParameters() && "Base union has parameters" );
1736
1737                        // check if type can be concretely instantiated; put substitutions into typeSubs
1738                        std::list< TypeExpr* > typeSubs;
1739                        if ( ! makeSubstitutions( *inst->get_baseParameters(), inst->get_parameters(), typeSubs ) ) {
1740                                deleteAll( typeSubs );
1741                                return inst;
1742                        }
1743
1744                        // make concrete instantiation of generic type
1745                        UnionDecl *concDecl = lookup( inst, typeSubs );
1746                        if ( ! concDecl ) {
1747                                // set concDecl to new type, insert type declaration into statements to add
1748                                concDecl = new UnionDecl( typeNamer.newName( inst->get_name() ) );
1749                                substituteMembers( inst->get_baseUnion()->get_members(), *inst->get_baseParameters(), typeSubs, concDecl->get_members() );
1750                                DeclMutator::addDeclaration( concDecl );
1751                                insert( inst, typeSubs, concDecl );
1752                        }
1753                        UnionInstType *newInst = new UnionInstType( inst->get_qualifiers(), concDecl->get_name() );
1754                        newInst->set_baseUnion( concDecl );
1755
1756                        deleteAll( typeSubs );
1757                        delete inst;
1758                        return newInst;
1759                }
1760
1761        //      /// Gets the base struct or union declaration for a member expression; NULL if not applicable
1762        //      AggregateDecl* getMemberBaseDecl( MemberExpr *memberExpr ) {
1763        //              // get variable for member aggregate
1764        //              VariableExpr *varExpr = dynamic_cast< VariableExpr* >( memberExpr->get_aggregate() );
1765        //              if ( ! varExpr ) return NULL;
1766        //
1767        //              // get object for variable
1768        //              ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1769        //              if ( ! objectDecl ) return NULL;
1770        //
1771        //              // get base declaration from object type
1772        //              Type *objectType = objectDecl->get_type();
1773        //              StructInstType *structType = dynamic_cast< StructInstType* >( objectType );
1774        //              if ( structType ) return structType->get_baseStruct();
1775        //              UnionInstType *unionType = dynamic_cast< UnionInstType* >( objectType );
1776        //              if ( unionType ) return unionType->get_baseUnion();
1777        //
1778        //              return NULL;
1779        //      }
1780        //
1781        //      /// Finds the declaration with the given name, returning decls.end() if none such
1782        //      std::list< Declaration* >::const_iterator findDeclNamed( const std::list< Declaration* > &decls, const std::string &name ) {
1783        //              for( std::list< Declaration* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
1784        //                      if ( (*decl)->get_name() == name ) return decl;
1785        //              }
1786        //              return decls.end();
1787        //      }
1788        //
1789        //      Expression* Instantiate::mutate( MemberExpr *memberExpr ) {
1790        //              // mutate, exiting early if no longer MemberExpr
1791        //              Expression *expr = Mutator::mutate( memberExpr );
1792        //              memberExpr = dynamic_cast< MemberExpr* >( expr );
1793        //              if ( ! memberExpr ) return expr;
1794        //
1795        //              // get declaration of member and base declaration of member, exiting early if not found
1796        //              AggregateDecl *memberBase = getMemberBaseDecl( memberExpr );
1797        //              if ( ! memberBase ) return memberExpr;
1798        //              DeclarationWithType *memberDecl = memberExpr->get_member();
1799        //              std::list< Declaration* >::const_iterator baseIt = findDeclNamed( memberBase->get_members(), memberDecl->get_name() );
1800        //              if ( baseIt == memberBase->get_members().end() ) return memberExpr;
1801        //              DeclarationWithType *baseDecl = dynamic_cast< DeclarationWithType* >( *baseIt );
1802        //              if ( ! baseDecl ) return memberExpr;
1803        //
1804        //              // check if stated type of the member is not the type of the member's declaration; if so, need a cast
1805        //              // this *SHOULD* be safe, I don't think anything but the void-replacements I put in for dtypes would make it past the typechecker
1806        //              SymTab::Indexer dummy;
1807        //              if ( ResolvExpr::typesCompatible( memberDecl->get_type(), baseDecl->get_type(), dummy ) ) return memberExpr;
1808        //              else return new CastExpr( memberExpr, memberDecl->get_type() );
1809        //      }
1810
1811                void GenericInstantiator::doBeginScope() {
1812                        DeclMutator::doBeginScope();
1813                        instantiations.beginScope();
1814                }
1815
1816                void GenericInstantiator::doEndScope() {
1817                        DeclMutator::doEndScope();
1818                        instantiations.endScope();
1819                }
1820
1821////////////////////////////////////////// PolyGenericCalculator ////////////////////////////////////////////////////
1822
1823                template< typename DeclClass >
1824                DeclClass * PolyGenericCalculator::handleDecl( DeclClass *decl, Type *type ) {
1825                        scopeTyVars.beginScope();
1826                        makeTyVarMap( type, scopeTyVars );
1827
1828                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1829
1830                        scopeTyVars.endScope();
1831                        return ret;
1832                }
1833
1834                ObjectDecl * PolyGenericCalculator::mutate( ObjectDecl *objectDecl ) {
1835                        return handleDecl( objectDecl, objectDecl->get_type() );
1836                }
1837
1838                DeclarationWithType * PolyGenericCalculator::mutate( FunctionDecl *functionDecl ) {
1839                        return handleDecl( functionDecl, functionDecl->get_functionType() );
1840                }
1841
1842                TypedefDecl * PolyGenericCalculator::mutate( TypedefDecl *typedefDecl ) {
1843                        return handleDecl( typedefDecl, typedefDecl->get_base() );
1844                }
1845
1846                TypeDecl * PolyGenericCalculator::mutate( TypeDecl *typeDecl ) {
1847                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1848                        return Mutator::mutate( typeDecl );
1849                }
1850
1851                Type * PolyGenericCalculator::mutate( PointerType *pointerType ) {
1852                        scopeTyVars.beginScope();
1853                        makeTyVarMap( pointerType, scopeTyVars );
1854
1855                        Type *ret = Mutator::mutate( pointerType );
1856
1857                        scopeTyVars.endScope();
1858                        return ret;
1859                }
1860
1861                Type * PolyGenericCalculator::mutate( FunctionType *funcType ) {
1862                        scopeTyVars.beginScope();
1863                        makeTyVarMap( funcType, scopeTyVars );
1864
1865                        // make sure that any type information passed into the function is accounted for
1866                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin(); fnParm != funcType->get_parameters().end(); ++fnParm ) {
1867                                // condition here duplicates that in Pass2::mutate( FunctionType* )
1868                                Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1869                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1870                                        knownLayouts.insert( mangleType( polyType ) );
1871                                }
1872                        }
1873                       
1874                        Type *ret = Mutator::mutate( funcType );
1875
1876                        scopeTyVars.endScope();
1877                        return ret;
1878                }
1879
1880                Statement *PolyGenericCalculator::mutate( DeclStmt *declStmt ) {
1881                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1882                                if ( findGeneric( objectDecl->get_type() ) ) {
1883                                        // change initialization of a polymorphic value object
1884                                        // to allocate storage with alloca
1885                                        Type *declType = objectDecl->get_type();
1886                                        UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
1887                                        alloc->get_args().push_back( new NameExpr( sizeofName( mangleType( declType ) ) ) );
1888
1889                                        delete objectDecl->get_init();
1890
1891                                        std::list<Expression*> designators;
1892                                        objectDecl->set_init( new SingleInit( alloc, designators ) );
1893                                }
1894                        }
1895                        return Mutator::mutate( declStmt );
1896                }
1897
1898                /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1899                long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1900                        long i = 0;
1901                        for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1902                                if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1903
1904                                if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1905                                        if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1906                                             || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1907                                        else continue;
1908                                } else return i;
1909                        }
1910                        return -1;
1911                }
1912
1913                /// Returns an index expression into the offset array for a type
1914                Expression *makeOffsetIndex( Type *objectType, long i ) {
1915                        std::stringstream offset_namer;
1916                        offset_namer << i;
1917                        ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1918                        UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1919                        fieldOffset->get_args().push_back( new NameExpr( offsetofName( mangleType( objectType ) ) ) );
1920                        fieldOffset->get_args().push_back( fieldIndex );
1921                        return fieldOffset;
1922                }
1923
1924                /// Returns an expression dereferenced n times
1925                Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1926                        for ( int i = 1; i < n; ++i ) {
1927                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1928                                derefExpr->get_args().push_back( derefdVar );
1929                                derefdVar = derefExpr;
1930                        }
1931                        return derefdVar;
1932                }
1933               
1934                Expression *PolyGenericCalculator::mutate( MemberExpr *memberExpr ) {
1935                        // mutate, exiting early if no longer MemberExpr
1936                        Expression *expr = Mutator::mutate( memberExpr );
1937                        memberExpr = dynamic_cast< MemberExpr* >( expr );
1938                        if ( ! memberExpr ) return expr;
1939
1940                        // get declaration for base struct, exiting early if not found
1941                        int varDepth;
1942                        VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
1943                        if ( ! varExpr ) return memberExpr;
1944                        ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1945                        if ( ! objectDecl ) return memberExpr;
1946
1947                        // only mutate member expressions for polymorphic types
1948                        int tyDepth;
1949                        Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
1950                        if ( ! objectType ) return memberExpr;
1951                        findGeneric( objectType ); // ensure layout for this type is available
1952
1953                        Expression *newMemberExpr = 0;
1954                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1955                                // look up offset index
1956                                long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1957                                if ( i == -1 ) return memberExpr;
1958
1959                                // replace member expression with pointer to base plus offset
1960                                UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1961                                fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1962                                fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1963                                newMemberExpr = fieldLoc;
1964                        } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1965                                // union members are all at offset zero, so build appropriately-dereferenced variable
1966                                newMemberExpr = makeDerefdVar( varExpr->clone(), varDepth );
1967                        } else return memberExpr;
1968                        assert( newMemberExpr );
1969
1970                        Type *memberType = memberExpr->get_member()->get_type();
1971                        if ( ! isPolyType( memberType, scopeTyVars ) ) {
1972                                // 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
1973                                CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1974                                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1975                                derefExpr->get_args().push_back( ptrCastExpr );
1976                                newMemberExpr = derefExpr;
1977                        }
1978
1979                        delete memberExpr;
1980                        return newMemberExpr;
1981                }
1982
1983                ObjectDecl *PolyGenericCalculator::makeVar( const std::string &name, Type *type, Initializer *init ) {
1984                        ObjectDecl *newObj = new ObjectDecl( name, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, init );
1985                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
1986                        return newObj;
1987                }
1988
1989                void PolyGenericCalculator::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1990                        for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1991                                if ( findGeneric( *param ) ) {
1992                                        // push size/align vars for a generic parameter back
1993                                        std::string paramName = mangleType( *param );
1994                                        layoutCall->get_args().push_back( new NameExpr( sizeofName( paramName ) ) );
1995                                        layoutCall->get_args().push_back( new NameExpr( alignofName( paramName ) ) );
1996                                } else {
1997                                        layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1998                                        layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1999                                }
2000                        }
2001                }
2002
2003                /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
2004                bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
2005                        bool hasDynamicLayout = false;
2006
2007                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
2008                        std::list< Expression* >::const_iterator typeParam = typeParams.begin();
2009                        for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
2010                                // skip non-otype parameters
2011                                if ( (*baseParam)->get_kind() != TypeDecl::Any ) continue;
2012                                TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
2013                                assert( typeExpr && "all otype parameters should be type expressions" );
2014
2015                                Type *type = typeExpr->get_type();
2016                                out.push_back( type );
2017                                if ( isPolyType( type ) ) hasDynamicLayout = true;
2018                        }
2019                        assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
2020
2021                        return hasDynamicLayout;
2022                }
2023
2024                bool PolyGenericCalculator::findGeneric( Type *ty ) {
2025                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( ty ) ) {
2026                                // duplicate logic from isPolyType()
2027                                if ( env ) {
2028                                        if ( Type *newType = env->lookup( typeInst->get_name() ) ) {
2029                                                return findGeneric( newType );
2030                                        } // if
2031                                } // if
2032                                if ( scopeTyVars.find( typeInst->get_name() ) != scopeTyVars.end() ) {
2033                                        // NOTE assumes here that getting put in the scopeTyVars included having the layout variables set
2034                                        return true;
2035                                }
2036                                return false;
2037                        } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
2038                                // check if this type already has a layout generated for it
2039                                std::string typeName = mangleType( ty );
2040                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
2041
2042                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
2043                                std::list< Type* > otypeParams;
2044                                if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
2045
2046                                // insert local variables for layout and generate call to layout function
2047                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
2048                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
2049
2050                                int n_members = structTy->get_baseStruct()->get_members().size();
2051                                if ( n_members == 0 ) {
2052                                        // all empty structs have the same layout - size 1, align 1
2053                                        makeVar( sizeofName( typeName ), layoutType, new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
2054                                        makeVar( alignofName( typeName ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from( (unsigned long)1 ) ) ) );
2055                                        // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
2056                                } else {
2057                                        ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
2058                                        ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
2059                                        ObjectDecl *offsetVar = makeVar( offsetofName( typeName ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from( n_members ) ), false, false ) );
2060
2061                                        // generate call to layout function
2062                                        UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( structTy->get_baseStruct() ) ) );
2063                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
2064                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
2065                                        layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
2066                                        addOtypeParamsToLayoutCall( layoutCall, otypeParams );
2067
2068                                        stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
2069                                }
2070
2071                                return true;
2072                        } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
2073                                // check if this type already has a layout generated for it
2074                                std::string typeName = mangleType( ty );
2075                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
2076
2077                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
2078                                std::list< Type* > otypeParams;
2079                                if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
2080
2081                                // insert local variables for layout and generate call to layout function
2082                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
2083                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
2084
2085                                ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
2086                                ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
2087
2088                                // generate call to layout function
2089                                UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( unionTy->get_baseUnion() ) ) );
2090                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
2091                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
2092                                addOtypeParamsToLayoutCall( layoutCall, otypeParams );
2093
2094                                stmtsToAdd.push_back( new ExprStmt( noLabels, layoutCall ) );
2095
2096                                return true;
2097                        }
2098
2099                        return false;
2100                }
2101
2102                Expression *PolyGenericCalculator::mutate( SizeofExpr *sizeofExpr ) {
2103                        Type *ty = sizeofExpr->get_type();
2104                        if ( findGeneric( ty ) ) {
2105                                Expression *ret = new NameExpr( sizeofName( mangleType( ty ) ) );
2106                                delete sizeofExpr;
2107                                return ret;
2108                        }
2109                        return sizeofExpr;
2110                }
2111
2112                Expression *PolyGenericCalculator::mutate( AlignofExpr *alignofExpr ) {
2113                        Type *ty = alignofExpr->get_type();
2114                        if ( findGeneric( ty ) ) {
2115                                Expression *ret = new NameExpr( alignofName( mangleType( ty ) ) );
2116                                delete alignofExpr;
2117                                return ret;
2118                        }
2119                        return alignofExpr;
2120                }
2121
2122                Expression *PolyGenericCalculator::mutate( OffsetofExpr *offsetofExpr ) {
2123                        // mutate, exiting early if no longer OffsetofExpr
2124                        Expression *expr = Mutator::mutate( offsetofExpr );
2125                        offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
2126                        if ( ! offsetofExpr ) return expr;
2127
2128                        // only mutate expressions for polymorphic structs/unions
2129                        Type *ty = offsetofExpr->get_type();
2130                        if ( ! findGeneric( ty ) ) return offsetofExpr;
2131                       
2132                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
2133                                // replace offsetof expression by index into offset array
2134                                long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
2135                                if ( i == -1 ) return offsetofExpr;
2136
2137                                Expression *offsetInd = makeOffsetIndex( ty, i );
2138                                delete offsetofExpr;
2139                                return offsetInd;
2140                        } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
2141                                // all union members are at offset zero
2142                                delete offsetofExpr;
2143                                return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
2144                        } else return offsetofExpr;
2145                }
2146
2147                Expression *PolyGenericCalculator::mutate( OffsetPackExpr *offsetPackExpr ) {
2148                        StructInstType *ty = offsetPackExpr->get_type();
2149
2150                        Expression *ret = 0;
2151                        if ( findGeneric( ty ) ) {
2152                                // pull offset back from generated type information
2153                                ret = new NameExpr( offsetofName( mangleType( ty ) ) );
2154                        } else {
2155                                std::string offsetName = offsetofName( mangleType( ty ) );
2156                                if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
2157                                        // use the already-generated offsets for this type
2158                                        ret = new NameExpr( offsetName );
2159                                } else {
2160                                        knownOffsets.insert( offsetName );
2161
2162                                        std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
2163                                        Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
2164
2165                                        // build initializer list for offset array
2166                                        std::list< Initializer* > inits;
2167                                        for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
2168                                                DeclarationWithType *memberDecl;
2169                                                if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
2170                                                        memberDecl = origMember->clone();
2171                                                } else {
2172                                                        memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
2173                                                }
2174                                                inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
2175                                        }
2176
2177                                        // build the offset array and replace the pack with a reference to it
2178                                        ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from( baseMembers.size() ) ), false, false ),
2179                                                        new ListInit( inits ) );
2180                                        ret = new VariableExpr( offsetArray );
2181                                }
2182                        }
2183
2184                        delete offsetPackExpr;
2185                        return ret;
2186                }
2187
2188                void PolyGenericCalculator::doBeginScope() {
2189                        knownLayouts.beginScope();
2190                        knownOffsets.beginScope();
2191                }
2192
2193                void PolyGenericCalculator::doEndScope() {
2194                        knownLayouts.endScope();
2195                        knownOffsets.endScope();
2196                }
2197
2198////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
2199
2200                template< typename DeclClass >
2201                DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
2202                        scopeTyVars.beginScope();
2203                        makeTyVarMap( type, scopeTyVars );
2204
2205                        DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
2206                        ScrubTyVars::scrub( decl, scopeTyVars );
2207
2208                        scopeTyVars.endScope();
2209                        return ret;
2210                }
2211
2212                ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
2213                        return handleDecl( objectDecl, objectDecl->get_type() );
2214                }
2215
2216                DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
2217                        return handleDecl( functionDecl, functionDecl->get_functionType() );
2218                }
2219
2220                TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
2221                        return handleDecl( typedefDecl, typedefDecl->get_base() );
2222                }
2223
2224                TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
2225//   Initializer *init = 0;
2226//   std::list< Expression *> designators;
2227//   scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2228//   if ( typeDecl->get_base() ) {
2229//     init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
2230//   }
2231//   return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
2232
2233                        scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
2234                        return Mutator::mutate( typeDecl );
2235                }
2236
2237                Type * Pass3::mutate( PointerType *pointerType ) {
2238                        scopeTyVars.beginScope();
2239                        makeTyVarMap( pointerType, scopeTyVars );
2240
2241                        Type *ret = Mutator::mutate( pointerType );
2242
2243                        scopeTyVars.endScope();
2244                        return ret;
2245                }
2246
2247                Type * Pass3::mutate( FunctionType *functionType ) {
2248                        scopeTyVars.beginScope();
2249                        makeTyVarMap( functionType, scopeTyVars );
2250
2251                        Type *ret = Mutator::mutate( functionType );
2252
2253                        scopeTyVars.endScope();
2254                        return ret;
2255                }
2256        } // anonymous namespace
2257} // namespace GenPoly
2258
2259// Local Variables: //
2260// tab-width: 4 //
2261// mode: c++ //
2262// compile-command: "make install" //
2263// End: //
Note: See TracBrowser for help on using the repository browser.