source: src/GenPoly/Box.cc @ fc72845d

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since fc72845d was fc72845d, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Convert Box Pass3 to PassVisitor?

  • Property mode set to 100644
File size: 87.9 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 : Wed Jun 21 15:49:59 2017
13// Update Count     : 346
14//
15
16#include <algorithm>                     // for mismatch
17#include <cassert>                       // for assert, strict_dynamic_cast
18#include <iostream>                      // for operator<<, stringstream
19#include <list>                          // for list, list<>::iterator, _Lis...
20#include <map>                           // for _Rb_tree_const_iterator, map
21#include <memory>                        // for auto_ptr
22#include <set>                           // for set
23#include <string>                        // for string, allocator, basic_string
24#include <utility>                       // for pair
25
26#include "Box.h"
27
28#include "CodeGen/OperatorTable.h"
29#include "Common/PassVisitor.h"          // for PassVisitor
30#include "Common/ScopedMap.h"            // for ScopedMap, ScopedMap<>::iter...
31#include "Common/SemanticError.h"        // for SemanticError
32#include "Common/UniqueName.h"           // for UniqueName
33#include "Common/utility.h"              // for toString
34#include "FindFunction.h"                // for findFunction, findAndReplace...
35#include "GenPoly/ErasableScopedMap.h"   // for ErasableScopedMap<>::const_i...
36#include "GenPoly/GenPoly.h"             // for TyVarMap, isPolyType, mangle...
37#include "InitTweak/InitTweak.h"         // for getFunctionName, isAssignment
38#include "Lvalue.h"                      // for generalizedLvalue
39#include "Parser/LinkageSpec.h"          // for C, Spec, Cforall, Intrinsic
40#include "PolyMutator.h"                 // for PolyMutator
41#include "ResolvExpr/TypeEnvironment.h"  // for EqvClass
42#include "ResolvExpr/typeops.h"          // for typesCompatible
43#include "ScopedSet.h"                   // for ScopedSet, ScopedSet<>::iter...
44#include "ScrubTyVars.h"                 // for ScrubTyVars
45#include "SymTab/Indexer.h"              // for Indexer
46#include "SymTab/Mangler.h"              // for Mangler
47#include "SynTree/Attribute.h"           // for Attribute
48#include "SynTree/Constant.h"            // for Constant
49#include "SynTree/Declaration.h"         // for DeclarationWithType, ObjectDecl
50#include "SynTree/Expression.h"          // for ApplicationExpr, UntypedExpr
51#include "SynTree/Initializer.h"         // for SingleInit, Initializer, Lis...
52#include "SynTree/Label.h"               // for Label, noLabels
53#include "SynTree/Mutator.h"             // for maybeMutate, Mutator, mutateAll
54#include "SynTree/Statement.h"           // for ExprStmt, DeclStmt, ReturnStmt
55#include "SynTree/SynTree.h"             // for UniqueId
56#include "SynTree/Type.h"                // for Type, FunctionType, PointerType
57#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution, operator<<
58
59namespace GenPoly {
60        namespace {
61                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
62
63                class BoxPass {
64                protected:
65                        BoxPass() : scopeTyVars( TypeDecl::Data{} ) {}
66                        TyVarMap scopeTyVars;
67                };
68
69                /// Adds layout-generation functions to polymorphic types
70                class LayoutFunctionBuilder final : public WithDeclsToAdd, public WithVisitorRef<LayoutFunctionBuilder>, public WithShortCircuiting {
71                        unsigned int functionNesting = 0;  // current level of nested functions
72                public:
73                        void previsit( FunctionDecl *functionDecl );
74                        void previsit( StructDecl *structDecl );
75                        void previsit( UnionDecl *unionDecl );
76                };
77
78                /// 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
79                class Pass1 final : public PolyMutator {
80                  public:
81                        Pass1();
82
83                        using PolyMutator::mutate;
84                        virtual Expression *mutate( ApplicationExpr *appExpr ) override;
85                        virtual Expression *mutate( AddressExpr *addrExpr ) override;
86                        virtual Expression *mutate( UntypedExpr *expr ) override;
87                        virtual DeclarationWithType* mutate( FunctionDecl *functionDecl ) override;
88                        virtual TypeDecl *mutate( TypeDecl *typeDecl ) override;
89                        virtual Expression *mutate( CommaExpr *commaExpr ) override;
90                        virtual Expression *mutate( ConditionalExpr *condExpr ) override;
91                        virtual Statement * mutate( ReturnStmt *returnStmt ) override;
92                        virtual Type *mutate( PointerType *pointerType ) override;
93                        virtual Type * mutate( FunctionType *functionType ) override;
94
95                        virtual void doBeginScope() override;
96                        virtual void doEndScope() override;
97                  private:
98                        /// Pass the extra type parameters from polymorphic generic arguments or return types into a function application
99                        void passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes );
100                        /// passes extra type parameters into a polymorphic function application
101                        void passTypeVars( ApplicationExpr *appExpr, Type *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
102                        /// wraps a function application with a new temporary for the out-parameter return value
103                        Expression *addRetParam( ApplicationExpr *appExpr, Type *retType, std::list< Expression *>::iterator &arg );
104                        /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
105                        void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
106                        /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
107                        /// If `doClone` is set to false, will not clone interior types
108                        Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
109                        /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
110                        Expression *addDynRetParam( ApplicationExpr *appExpr, Type *polyType, std::list< Expression *>::iterator &arg );
111                        Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
112                        void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
113                        void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
114                        void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
115                        /// Stores assignment operators from assertion list in local map of assignment operations
116                        void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
117                        FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
118                        /// Replaces intrinsic operator functions with their arithmetic desugaring
119                        Expression *handleIntrinsics( ApplicationExpr *appExpr );
120                        /// Inserts a new temporary variable into the current scope with an auto-generated name
121                        ObjectDecl *makeTemporary( Type *type );
122
123                        ScopedMap< std::string, DeclarationWithType* > adapters;     ///< Set of adapter functions in the current scope
124
125                        std::map< ApplicationExpr *, Expression * > retVals;
126
127                        DeclarationWithType *retval;
128                        UniqueName tempNamer;
129                };
130
131                /// * Moves polymorphic returns in function types to pointer-type parameters
132                /// * adds type size and assertion parameters to parameter lists
133                class Pass2 final : public PolyMutator {
134                  public:
135                        template< typename DeclClass >
136                        DeclClass *handleDecl( DeclClass *decl );
137                        template< typename AggDecl >
138                        AggDecl * handleAggDecl( AggDecl * aggDecl );
139
140                        typedef PolyMutator Parent;
141                        using Parent::mutate;
142                        virtual DeclarationWithType *mutate( FunctionDecl *functionDecl ) override;
143                        virtual ObjectDecl *mutate( ObjectDecl *objectDecl ) override;
144                        virtual StructDecl *mutate( StructDecl *structDecl ) override;
145                        virtual UnionDecl *mutate( UnionDecl *unionDecl ) override;
146                        virtual TraitDecl *mutate( TraitDecl *unionDecl ) override;
147                        virtual TypeDecl *mutate( TypeDecl *typeDecl ) override;
148                        virtual TypedefDecl *mutate( TypedefDecl *typedefDecl ) override;
149                        virtual Type *mutate( PointerType *pointerType ) override;
150                        virtual Type *mutate( FunctionType *funcType ) override;
151
152                  private:
153                        void addAdapters( FunctionType *functionType );
154
155                        std::map< UniqueId, std::string > adapterName;
156                };
157
158                /// Replaces member and size/align/offsetof expressions on polymorphic generic types with calculated expressions.
159                /// * Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference
160                /// * Calculates polymorphic offsetof expressions from offset array
161                /// * Inserts dynamic calculation of polymorphic type layouts where needed
162                class PolyGenericCalculator final : public WithGuards, public WithVisitorRef<PolyGenericCalculator>, public WithStmtsToAdd, public WithDeclsToAdd, public WithTypeSubstitution {
163                public:
164                        PolyGenericCalculator();
165
166                        void premutate( ObjectDecl *objectDecl );
167                        void premutate( FunctionDecl *functionDecl );
168                        void premutate( TypedefDecl *objectDecl );
169                        void premutate( TypeDecl *objectDecl );
170                        Declaration * postmutate( TypeDecl *TraitDecl );
171                        void premutate( PointerType *pointerType );
172                        void premutate( FunctionType *funcType );
173                        void premutate( DeclStmt *declStmt );
174                        Expression *postmutate( MemberExpr *memberExpr );
175                        Expression *postmutate( SizeofExpr *sizeofExpr );
176                        Expression *postmutate( AlignofExpr *alignofExpr );
177                        Expression *postmutate( OffsetofExpr *offsetofExpr );
178                        Expression *postmutate( OffsetPackExpr *offsetPackExpr );
179
180                        void beginScope();
181                        void endScope();
182
183                private:
184                        /// Makes a new variable in the current scope with the given name, type & optional initializer
185                        ObjectDecl *makeVar( const std::string &name, Type *type, Initializer *init = 0 );
186                        /// returns true if the type has a dynamic layout; such a layout will be stored in appropriately-named local variables when the function returns
187                        bool findGeneric( Type *ty );
188                        /// adds type parameters to the layout call; will generate the appropriate parameters if needed
189                        void addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams );
190
191                        /// Enters a new scope for type-variables, adding the type variables from ty
192                        void beginTypeScope( Type *ty );
193                        /// Exits the type-variable scope
194                        void endTypeScope();
195                        /// Enters a new scope for knowLayouts and knownOffsets and queues exit calls
196                        void beginGenericScope();
197
198                        ScopedSet< std::string > knownLayouts;          ///< Set of generic type layouts known in the current scope, indexed by sizeofName
199                        ScopedSet< std::string > knownOffsets;          ///< Set of non-generic types for which the offset array exists in the current scope, indexed by offsetofName
200                        UniqueName bufNamer;                           ///< Namer for VLA buffers
201                        TyVarMap scopeTyVars;
202                };
203
204                /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, sizeof expressions of polymorphic types with the proper variable, and strips fields from generic struct declarations.
205                struct Pass3 final : public BoxPass, public WithGuards {
206                        template< typename DeclClass >
207                        void handleDecl( DeclClass * decl, Type * type );
208
209                        void premutate( ObjectDecl * objectDecl );
210                        void premutate( FunctionDecl * functionDecl );
211                        void premutate( TypedefDecl * typedefDecl );
212                        void premutate( StructDecl * structDecl );
213                        void premutate( UnionDecl * unionDecl );
214                        void premutate( TypeDecl * typeDecl );
215                        void premutate( PointerType * pointerType );
216                        void premutate( FunctionType * funcType );
217                };
218        } // anonymous namespace
219
220        /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
221        template< typename MutatorType >
222        inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
223                bool seenIntrinsic = false;
224                SemanticError errors;
225                for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
226                        try {
227                                if ( *i ) {
228                                        if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
229                                                seenIntrinsic = true;
230                                        } else if ( seenIntrinsic ) {
231                                                seenIntrinsic = false; // break on this line when debugging for end of prelude
232                                        }
233
234                                        *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
235                                        assert( *i );
236                                } // if
237                        } catch( SemanticError &e ) {
238                                e.set_location( (*i)->location );
239                                errors.append( e );
240                        } // try
241                } // for
242                if ( ! errors.isEmpty() ) {
243                        throw errors;
244                } // if
245        }
246
247        void box( std::list< Declaration *>& translationUnit ) {
248                PassVisitor<LayoutFunctionBuilder> layoutBuilder;
249                Pass1 pass1;
250                Pass2 pass2;
251                PassVisitor<PolyGenericCalculator> polyCalculator;
252                PassVisitor<Pass3> pass3;
253
254                acceptAll( translationUnit, layoutBuilder );
255                mutateTranslationUnit/*All*/( translationUnit, pass1 );
256                mutateTranslationUnit/*All*/( translationUnit, pass2 );
257                mutateAll( translationUnit, polyCalculator );
258                mutateAll( translationUnit, pass3 );
259        }
260
261        ////////////////////////////////// LayoutFunctionBuilder ////////////////////////////////////////////
262
263        void LayoutFunctionBuilder::previsit( FunctionDecl *functionDecl ) {
264                visit_children = false;
265                maybeAccept( functionDecl->get_functionType(), *visitor );
266                ++functionNesting;
267                maybeAccept( functionDecl->get_statements(), *visitor );
268                --functionNesting;
269        }
270
271        /// Get a list of type declarations that will affect a layout function
272        std::list< TypeDecl* > takeOtypeOnly( std::list< TypeDecl* > &decls ) {
273                std::list< TypeDecl * > otypeDecls;
274
275                for ( std::list< TypeDecl* >::const_iterator decl = decls.begin(); decl != decls.end(); ++decl ) {
276                        if ( (*decl)->isComplete() ) {
277                                otypeDecls.push_back( *decl );
278                        }
279                }
280
281                return otypeDecls;
282        }
283
284        /// Adds parameters for otype layout to a function type
285        void addOtypeParams( FunctionType *layoutFnType, std::list< TypeDecl* > &otypeParams ) {
286                BasicType sizeAlignType( Type::Qualifiers(), BasicType::LongUnsignedInt );
287
288                for ( std::list< TypeDecl* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
289                        TypeInstType paramType( Type::Qualifiers(), (*param)->get_name(), *param );
290                        std::string paramName = mangleType( &paramType );
291                        layoutFnType->get_parameters().push_back( new ObjectDecl( sizeofName( paramName ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
292                        layoutFnType->get_parameters().push_back( new ObjectDecl( alignofName( paramName ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignType.clone(), 0 ) );
293                }
294        }
295
296        /// Builds a layout function declaration
297        FunctionDecl *buildLayoutFunctionDecl( AggregateDecl *typeDecl, unsigned int functionNesting, FunctionType *layoutFnType ) {
298                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
299                // because each unit generates copies of the default routines for each aggregate.
300                FunctionDecl *layoutDecl = new FunctionDecl( layoutofName( typeDecl ),
301                                                                                                         functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static ),
302                                                                                                         LinkageSpec::AutoGen, layoutFnType, new CompoundStmt( noLabels ),
303                                                                                                         std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
304                layoutDecl->fixUniqueId();
305                return layoutDecl;
306        }
307
308        /// Makes a unary operation
309        Expression *makeOp( const std::string &name, Expression *arg ) {
310                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
311                expr->get_args().push_back( arg );
312                return expr;
313        }
314
315        /// Makes a binary operation
316        Expression *makeOp( const std::string &name, Expression *lhs, Expression *rhs ) {
317                UntypedExpr *expr = new UntypedExpr( new NameExpr( name ) );
318                expr->get_args().push_back( lhs );
319                expr->get_args().push_back( rhs );
320                return expr;
321        }
322
323        /// Returns the dereference of a local pointer variable
324        Expression *derefVar( ObjectDecl *var ) {
325                return makeOp( "*?", new VariableExpr( var ) );
326        }
327
328        /// makes an if-statement with a single-expression if-block and no then block
329        Statement *makeCond( Expression *cond, Expression *ifPart ) {
330                return new IfStmt( noLabels, cond, new ExprStmt( noLabels, ifPart ), 0 );
331        }
332
333        /// makes a statement that assigns rhs to lhs if lhs < rhs
334        Statement *makeAssignMax( Expression *lhs, Expression *rhs ) {
335                return makeCond( makeOp( "?<?", lhs, rhs ), makeOp( "?=?", lhs->clone(), rhs->clone() ) );
336        }
337
338        /// makes a statement that aligns lhs to rhs (rhs should be an integer power of two)
339        Statement *makeAlignTo( Expression *lhs, Expression *rhs ) {
340                // check that the lhs is zeroed out to the level of rhs
341                Expression *ifCond = makeOp( "?&?", lhs, makeOp( "?-?", rhs, new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
342                // if not aligned, increment to alignment
343                Expression *ifExpr = makeOp( "?+=?", lhs->clone(), makeOp( "?-?", rhs->clone(), ifCond->clone() ) );
344                return makeCond( ifCond, ifExpr );
345        }
346
347        /// adds an expression to a compound statement
348        void addExpr( CompoundStmt *stmts, Expression *expr ) {
349                stmts->get_kids().push_back( new ExprStmt( noLabels, expr ) );
350        }
351
352        /// adds a statement to a compound statement
353        void addStmt( CompoundStmt *stmts, Statement *stmt ) {
354                stmts->get_kids().push_back( stmt );
355        }
356
357        void LayoutFunctionBuilder::previsit( StructDecl *structDecl ) {
358                // do not generate layout function for "empty" tag structs
359                visit_children = false;
360                if ( structDecl->get_members().empty() ) return;
361
362                // get parameters that can change layout, exiting early if none
363                std::list< TypeDecl* > otypeParams = takeOtypeOnly( structDecl->get_parameters() );
364                if ( otypeParams.empty() ) return;
365
366                // build layout function signature
367                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
368                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
369                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
370
371                ObjectDecl *sizeParam = new ObjectDecl( sizeofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
372                layoutFnType->get_parameters().push_back( sizeParam );
373                ObjectDecl *alignParam = new ObjectDecl( alignofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
374                layoutFnType->get_parameters().push_back( alignParam );
375                ObjectDecl *offsetParam = new ObjectDecl( offsetofName( structDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
376                layoutFnType->get_parameters().push_back( offsetParam );
377                addOtypeParams( layoutFnType, otypeParams );
378
379                // build function decl
380                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( structDecl, functionNesting, layoutFnType );
381
382                // calculate struct layout in function body
383
384                // initialize size and alignment to 0 and 1 (will have at least one member to re-edit size)
385                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant::from_ulong( 0 ) ) ) );
386                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
387                unsigned long n_members = 0;
388                bool firstMember = true;
389                for ( std::list< Declaration* >::const_iterator member = structDecl->get_members().begin(); member != structDecl->get_members().end(); ++member ) {
390                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
391                        assert( dwt );
392                        Type *memberType = dwt->get_type();
393
394                        if ( firstMember ) {
395                                firstMember = false;
396                        } else {
397                                // make sure all members after the first (automatically aligned at 0) are properly padded for alignment
398                                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), new AlignofExpr( memberType->clone() ) ) );
399                        }
400
401                        // place current size in the current offset index
402                        addExpr( layoutDecl->get_statements(), makeOp( "?=?", makeOp( "?[?]", new VariableExpr( offsetParam ), new ConstantExpr( Constant::from_ulong( n_members ) ) ),
403                                                                              derefVar( sizeParam ) ) );
404                        ++n_members;
405
406                        // add member size to current size
407                        addExpr( layoutDecl->get_statements(), makeOp( "?+=?", derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
408
409                        // take max of member alignment and global alignment
410                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
411                }
412                // make sure the type is end-padded to a multiple of its alignment
413                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
414
415                declsToAddAfter.push_back( layoutDecl );
416        }
417
418        void LayoutFunctionBuilder::previsit( UnionDecl *unionDecl ) {
419                // do not generate layout function for "empty" tag unions
420                visit_children = false;
421                if ( unionDecl->get_members().empty() ) return;
422
423                // get parameters that can change layout, exiting early if none
424                std::list< TypeDecl* > otypeParams = takeOtypeOnly( unionDecl->get_parameters() );
425                if ( otypeParams.empty() ) return;
426
427                // build layout function signature
428                FunctionType *layoutFnType = new FunctionType( Type::Qualifiers(), false );
429                BasicType *sizeAlignType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
430                PointerType *sizeAlignOutType = new PointerType( Type::Qualifiers(), sizeAlignType );
431
432                ObjectDecl *sizeParam = new ObjectDecl( sizeofName( unionDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType, 0 );
433                layoutFnType->get_parameters().push_back( sizeParam );
434                ObjectDecl *alignParam = new ObjectDecl( alignofName( unionDecl->get_name() ), Type::StorageClasses(), LinkageSpec::Cforall, 0, sizeAlignOutType->clone(), 0 );
435                layoutFnType->get_parameters().push_back( alignParam );
436                addOtypeParams( layoutFnType, otypeParams );
437
438                // build function decl
439                FunctionDecl *layoutDecl = buildLayoutFunctionDecl( unionDecl, functionNesting, layoutFnType );
440
441                // calculate union layout in function body
442                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( sizeParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
443                addExpr( layoutDecl->get_statements(), makeOp( "?=?", derefVar( alignParam ), new ConstantExpr( Constant::from_ulong( 1 ) ) ) );
444                for ( std::list< Declaration* >::const_iterator member = unionDecl->get_members().begin(); member != unionDecl->get_members().end(); ++member ) {
445                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member );
446                        assert( dwt );
447                        Type *memberType = dwt->get_type();
448
449                        // take max member size and global size
450                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( sizeParam ), new SizeofExpr( memberType->clone() ) ) );
451
452                        // take max of member alignment and global alignment
453                        addStmt( layoutDecl->get_statements(), makeAssignMax( derefVar( alignParam ), new AlignofExpr( memberType->clone() ) ) );
454                }
455                // make sure the type is end-padded to a multiple of its alignment
456                addStmt( layoutDecl->get_statements(), makeAlignTo( derefVar( sizeParam ), derefVar( alignParam ) ) );
457
458                declsToAddAfter.push_back( layoutDecl );
459        }
460
461        ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
462
463        namespace {
464                std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
465                        std::stringstream name;
466
467                        // NOTE: this function previously used isPolyObj, which failed to produce
468                        // the correct thing in some situations. It's not clear to me why this wasn't working.
469
470                        // if the return type or a parameter type involved polymorphic types, then the adapter will need
471                        // to take those polymorphic types as pointers. Therefore, there can be two different functions
472                        // with the same mangled name, so we need to further mangle the names.
473                        for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
474                                if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
475                                        name << "P";
476                                } else {
477                                        name << "M";
478                                }
479                        }
480                        name << "_";
481                        std::list< DeclarationWithType *> &paramList = function->get_parameters();
482                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
483                                if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
484                                        name << "P";
485                                } else {
486                                        name << "M";
487                                }
488                        } // for
489                        return name.str();
490                }
491
492                std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
493                        return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
494                }
495
496                std::string makeAdapterName( const std::string &mangleName ) {
497                        return "_adapter" + mangleName;
498                }
499
500                Pass1::Pass1() : tempNamer( "_temp" ) {}
501
502                DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
503                        if ( functionDecl->get_statements() ) {         // empty routine body ?
504                                // std::cerr << "mutating function: " << functionDecl->get_mangleName() << std::endl;
505                                doBeginScope();
506                                scopeTyVars.beginScope();
507
508                                DeclarationWithType *oldRetval = retval;
509
510                                // process polymorphic return value
511                                retval = nullptr;
512                                if ( isDynRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() != LinkageSpec::C ) {
513                                        retval = functionDecl->get_functionType()->get_returnVals().front();
514
515                                        // give names to unnamed return values
516                                        if ( retval->get_name() == "" ) {
517                                                retval->set_name( "_retparm" );
518                                                retval->set_linkage( LinkageSpec::C );
519                                        } // if
520                                } // if
521
522                                FunctionType *functionType = functionDecl->get_functionType();
523                                makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
524
525                                std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
526                                std::list< FunctionType *> functions;
527                                for ( Type::ForallList::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
528                                        for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
529                                                findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
530                                        } // for
531                                } // for
532                                for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
533                                        findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
534                                } // for
535
536                                for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
537                                        std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
538                                        if ( adapters.find( mangleName ) == adapters.end() ) {
539                                                std::string adapterName = makeAdapterName( mangleName );
540                                                adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, nullptr, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), nullptr ) ) );
541                                        } // if
542                                } // for
543
544                                functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
545
546                                scopeTyVars.endScope();
547                                retval = oldRetval;
548                                doEndScope();
549                                // std::cerr << "end function: " << functionDecl->get_mangleName() << std::endl;
550                        } // if
551                        return functionDecl;
552                }
553
554                TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
555                        addToTyVarMap( typeDecl, scopeTyVars );
556                        return dynamic_cast<TypeDecl*>( Mutator::mutate( typeDecl ) );
557                }
558
559                Expression *Pass1::mutate( CommaExpr *commaExpr ) {
560                        // Attempting to find application expressions that were mutated by the copy constructor passes
561                        // to use an explicit return variable, so that the variable can be reused as a parameter to the
562                        // call rather than creating a new temp variable. Previously this step was an optimization, but
563                        // with the introduction of tuples and UniqueExprs, it is necessary to ensure that they use the same variable.
564                        // Essentially, looking for pattern: (x=f(...), x)
565                        // To compound the issue, the right side can be *x, etc. because of lvalue-returning functions
566                        if ( UntypedExpr * assign = dynamic_cast< UntypedExpr * >( commaExpr->get_arg1() ) ) {
567                                if ( CodeGen::isAssignment( InitTweak::getFunctionName( assign ) ) ) {
568                                        assert( assign->get_args().size() == 2 );
569                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( assign->get_args().back() ) ) {
570                                                // first argument is assignable, so it must be an lvalue, so it should be legal to take its address.
571                                                retVals[appExpr] = assign->get_args().front();
572                                        }
573                                }
574                        }
575
576                        commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
577                        commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
578                        return commaExpr;
579                }
580
581                Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
582                        condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
583                        condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
584                        condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
585                        return condExpr;
586
587                }
588
589                void Pass1::passArgTypeVars( ApplicationExpr *appExpr, Type *parmType, Type *argBaseType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars, std::set< std::string > &seenTypes ) {
590                        Type *polyType = isPolyType( parmType, exprTyVars );
591                        if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
592                                std::string typeName = mangleType( polyType );
593                                if ( seenTypes.count( typeName ) ) return;
594
595                                arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
596                                arg++;
597                                arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
598                                arg++;
599                                if ( dynamic_cast< StructInstType* >( polyType ) ) {
600                                        if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
601                                                // zero-length arrays are forbidden by C, so don't pass offset for empty struct
602                                                if ( ! argBaseStructType->get_baseStruct()->get_members().empty() ) {
603                                                        arg = appExpr->get_args().insert( arg, new OffsetPackExpr( argBaseStructType->clone() ) );
604                                                        arg++;
605                                                }
606                                        } else {
607                                                throw SemanticError( "Cannot pass non-struct type for generic struct: ", argBaseType );
608                                        }
609                                }
610
611                                seenTypes.insert( typeName );
612                        }
613                }
614
615                void Pass1::passTypeVars( ApplicationExpr *appExpr, Type *polyRetType, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
616                        // pass size/align for type variables
617                        for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
618                                ResolvExpr::EqvClass eqvClass;
619                                assert( env );
620                                if ( tyParm->second.isComplete ) {
621                                        Type *concrete = env->lookup( tyParm->first );
622                                        if ( concrete ) {
623                                                arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
624                                                arg++;
625                                                arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
626                                                arg++;
627                                        } else {
628                                                // xxx - should this be an assertion?
629                                                throw SemanticError( toString( *env, "\nunbound type variable: ", tyParm->first, " in application " ), appExpr );
630                                        } // if
631                                } // if
632                        } // for
633
634                        // add size/align for generic types to parameter list
635                        if ( ! appExpr->get_function()->has_result() ) return;
636                        FunctionType *funcType = getFunctionType( appExpr->get_function()->get_result() );
637                        assert( funcType );
638
639                        std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
640                        std::list< Expression* >::const_iterator fnArg = arg;
641                        std::set< std::string > seenTypes; ///< names for generic types we've seen
642
643                        // a polymorphic return type may need to be added to the argument list
644                        if ( polyRetType ) {
645                                Type *concRetType = replaceWithConcrete( appExpr, polyRetType );
646                                passArgTypeVars( appExpr, polyRetType, concRetType, arg, exprTyVars, seenTypes );
647                                ++fnArg; // skip the return parameter in the argument list
648                        }
649
650                        // add type information args for presently unseen types in parameter list
651                        for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
652                                if ( ! (*fnArg)->get_result() ) continue;
653                                Type * argType = (*fnArg)->get_result();
654                                passArgTypeVars( appExpr, (*fnParm)->get_type(), argType, arg, exprTyVars, seenTypes );
655                        }
656                }
657
658                ObjectDecl *Pass1::makeTemporary( Type *type ) {
659                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, type, 0 );
660                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
661                        return newObj;
662                }
663
664                Expression *Pass1::addRetParam( ApplicationExpr *appExpr, Type *retType, std::list< Expression *>::iterator &arg ) {
665                        // Create temporary to hold return value of polymorphic function and produce that temporary as a result
666                        // using a comma expression.
667                        assert( retType );
668
669                        Expression * paramExpr = nullptr;
670                        // try to use existing return value parameter if it exists, otherwise create a new temporary
671                        if ( retVals.count( appExpr ) ) {
672                                paramExpr = retVals[appExpr]->clone();
673                        } else {
674                                ObjectDecl *newObj = makeTemporary( retType->clone() );
675                                paramExpr = new VariableExpr( newObj );
676                        }
677                        Expression * retExpr = paramExpr->clone();
678
679                        // If the type of the temporary is not polymorphic, box temporary by taking its address;
680                        // otherwise the temporary is already boxed and can be used directly.
681                        if ( ! isPolyType( paramExpr->get_result(), scopeTyVars, env ) ) {
682                                paramExpr = new AddressExpr( paramExpr );
683                        } // if
684                        arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
685                        arg++;
686                        // Build a comma expression to call the function and emulate a normal return.
687                        CommaExpr *commaExpr = new CommaExpr( appExpr, retExpr );
688                        commaExpr->set_env( appExpr->get_env() );
689                        appExpr->set_env( 0 );
690                        return commaExpr;
691                }
692
693                void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
694                        for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
695                                TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
696                                assertf(paramType, "Aggregate parameters should be type expressions");
697                                paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
698                        }
699                }
700
701                Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
702                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
703                                Type *concrete = env->lookup( typeInst->get_name() );
704                                if ( concrete == 0 ) {
705                                        return typeInst;
706                                } // if
707                                return concrete;
708                        } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
709                                if ( doClone ) {
710                                        structType = structType->clone();
711                                }
712                                replaceParametersWithConcrete( appExpr, structType->get_parameters() );
713                                return structType;
714                        } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
715                                if ( doClone ) {
716                                        unionType = unionType->clone();
717                                }
718                                replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
719                                return unionType;
720                        }
721                        return type;
722                }
723
724                Expression *Pass1::addDynRetParam( ApplicationExpr *appExpr, Type *dynType, std::list< Expression *>::iterator &arg ) {
725                        assert( env );
726                        Type *concrete = replaceWithConcrete( appExpr, dynType );
727                        // add out-parameter for return value
728                        return addRetParam( appExpr, concrete, arg );
729                }
730
731                Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
732                        Expression *ret = appExpr;
733//                      if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
734                        if ( isDynRet( function, tyVars ) ) {
735                                ret = addRetParam( appExpr, function->get_returnVals().front()->get_type(), arg );
736                        } // if
737                        std::string mangleName = mangleAdapterName( function, tyVars );
738                        std::string adapterName = makeAdapterName( mangleName );
739
740                        // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
741                        Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
742                        appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
743                        appExpr->set_function( new NameExpr( adapterName ) ); // xxx - result is never set on NameExpr
744
745                        return ret;
746                }
747
748                void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
749                        assertf( arg->has_result(), "arg does not have result: %s", toString( arg ).c_str() );
750                        if ( isPolyType( param, exprTyVars ) ) {
751                                Type * newType = arg->get_result()->clone();
752                                if ( env ) env->apply( newType );
753                                std::unique_ptr<Type> manager( newType );
754                                if ( isPolyType( newType ) ) {
755                                        // if the argument's type is polymorphic, we don't need to box again!
756                                        return;
757                                } else if ( arg->get_result()->get_lvalue() ) {
758                                        // argument expression may be CFA lvalue, but not C lvalue -- apply generalizedLvalue transformations.
759                                        // if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( arg ) ) {
760                                        //      if ( dynamic_cast<ArrayType *>( varExpr->var->get_type() ) ){
761                                        //              // temporary hack - don't box arrays, because &arr is not the same as &arr[0]
762                                        //              return;
763                                        //      }
764                                        // }
765                                        arg =  generalizedLvalue( new AddressExpr( arg ) );
766                                        if ( ! ResolvExpr::typesCompatible( param, arg->get_result(), SymTab::Indexer() ) ) {
767                                                // silence warnings by casting boxed parameters when the actual type does not match up with the formal type.
768                                                arg = new CastExpr( arg, param->clone() );
769                                        }
770                                } else {
771                                        // use type computed in unification to declare boxed variables
772                                        Type * newType = param->clone();
773                                        if ( env ) env->apply( newType );
774                                        ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, newType, 0 );
775                                        newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
776                                        stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
777                                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) ); // TODO: why doesn't this just use initialization syntax?
778                                        assign->get_args().push_back( new VariableExpr( newObj ) );
779                                        assign->get_args().push_back( arg );
780                                        stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
781                                        arg = new AddressExpr( new VariableExpr( newObj ) );
782                                } // if
783                        } // if
784                }
785
786                /// cast parameters to polymorphic functions so that types are replaced with
787                /// void * if they are type parameters in the formal type.
788                /// this gets rid of warnings from gcc.
789                void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
790                        if ( getFunctionType( formal ) ) {
791                                Type * newType = formal->clone();
792                                newType = ScrubTyVars::scrub( newType, tyVars );
793                                actual = new CastExpr( actual, newType );
794                        } // if
795                }
796
797                void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
798                        for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
799                                assertf( arg != appExpr->get_args().end(), "boxParams: missing argument for param %s to %s in %s", toString( *param ).c_str(), toString( function ).c_str(), toString( appExpr ).c_str() );
800                                addCast( *arg, (*param)->get_type(), exprTyVars );
801                                boxParam( (*param)->get_type(), *arg, exprTyVars );
802                        } // for
803                }
804
805                void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
806                        std::list< Expression *>::iterator cur = arg;
807                        for ( Type::ForallList::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
808                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
809                                        InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
810                                        if ( inferParam == appExpr->get_inferParams().end() ) {
811                                                std::cerr << "looking for assertion: " << (*assert) << std::endl << appExpr << std::endl;
812                                        }
813                                        assertf( inferParam != appExpr->get_inferParams().end(), "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
814                                        Expression *newExpr = inferParam->second.expr->clone();
815                                        addCast( newExpr, (*assert)->get_type(), tyVars );
816                                        boxParam( (*assert)->get_type(), newExpr, tyVars );
817                                        appExpr->get_args().insert( cur, newExpr );
818                                } // for
819                        } // for
820                }
821
822                void makeRetParm( FunctionType *funcType ) {
823                        DeclarationWithType *retParm = funcType->get_returnVals().front();
824
825                        // make a new parameter that is a pointer to the type of the old return value
826                        retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
827                        funcType->get_parameters().push_front( retParm );
828
829                        // we don't need the return value any more
830                        funcType->get_returnVals().clear();
831                }
832
833                FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
834                        // actually make the adapter type
835                        FunctionType *adapter = adaptee->clone();
836//                      if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
837                        if ( isDynRet( adapter, tyVars ) ) {
838                                makeRetParm( adapter );
839                        } // if
840                        adapter->get_parameters().push_front( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
841                        return adapter;
842                }
843
844                Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
845                        assert( param );
846                        assert( arg );
847                        if ( isPolyType( realParam->get_type(), tyVars ) ) {
848                                if ( ! isPolyType( arg->get_type() ) ) {
849                                        UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
850                                        deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
851                                        deref->set_result( arg->get_type()->clone() );
852                                        return deref;
853                                } // if
854                        } // if
855                        return new VariableExpr( param );
856                }
857
858                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 ) {
859                        UniqueName paramNamer( "_p" );
860                        for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
861                                if ( (*param)->get_name() == "" ) {
862                                        (*param)->set_name( paramNamer.newName() );
863                                        (*param)->set_linkage( LinkageSpec::C );
864                                } // if
865                                adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
866                        } // for
867                }
868
869                FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
870                        FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
871                        adapterType = ScrubTyVars::scrub( adapterType, tyVars );
872                        DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
873                        adapteeDecl->set_name( "_adaptee" );
874                        ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
875                        Statement *bodyStmt;
876
877                        Type::ForallList::iterator tyArg = realType->get_forall().begin();
878                        Type::ForallList::iterator tyParam = adapterType->get_forall().begin();
879                        Type::ForallList::iterator realTyParam = adaptee->get_forall().begin();
880                        for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
881                                assert( tyArg != realType->get_forall().end() );
882                                std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
883                                std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
884                                std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
885                                for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
886                                        assert( assertArg != (*tyArg)->get_assertions().end() );
887                                        adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
888                                } // for
889                        } // for
890
891                        std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
892                        std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
893                        std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
894                        param++;                // skip adaptee parameter in the adapter type
895                        if ( realType->get_returnVals().empty() ) {
896                                // void return
897                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
898                                bodyStmt = new ExprStmt( noLabels, adapteeApp );
899                        } else if ( isDynType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
900                                // return type T
901                                if ( (*param)->get_name() == "" ) {
902                                        (*param)->set_name( "_ret" );
903                                        (*param)->set_linkage( LinkageSpec::C );
904                                } // if
905                                UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
906                                UntypedExpr *deref = UntypedExpr::createDeref( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
907                                assign->get_args().push_back( deref );
908                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
909                                assign->get_args().push_back( adapteeApp );
910                                bodyStmt = new ExprStmt( noLabels, assign );
911                        } else {
912                                // adapter for a function that returns a monomorphic value
913                                addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
914                                bodyStmt = new ReturnStmt( noLabels, adapteeApp );
915                        } // if
916                        CompoundStmt *adapterBody = new CompoundStmt( noLabels );
917                        adapterBody->get_kids().push_back( bodyStmt );
918                        std::string adapterName = makeAdapterName( mangleName );
919                        return new FunctionDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, adapterType, adapterBody );
920                }
921
922                void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
923                        // collect a list of function types passed as parameters or implicit parameters (assertions)
924                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
925                        std::list< FunctionType *> functions;
926                        for ( Type::ForallList::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
927                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
928                                        findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
929                                } // for
930                        } // for
931                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
932                                findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
933                        } // for
934
935                        // parameter function types for which an appropriate adapter has been generated.  we cannot use the types
936                        // after applying substitutions, since two different parameter types may be unified to the same type
937                        std::set< std::string > adaptersDone;
938
939                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
940                                FunctionType *originalFunction = (*funType)->clone();
941                                FunctionType *realFunction = (*funType)->clone();
942                                std::string mangleName = SymTab::Mangler::mangle( realFunction );
943
944                                // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
945                                // pre-substitution parameter function type.
946                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
947                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
948
949                                        // apply substitution to type variables to figure out what the adapter's type should look like
950                                        assert( env );
951                                        env->apply( realFunction );
952                                        mangleName = SymTab::Mangler::mangle( realFunction );
953                                        mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
954
955                                        typedef ScopedMap< std::string, DeclarationWithType* >::iterator AdapterIter;
956                                        AdapterIter adapter = adapters.find( mangleName );
957                                        if ( adapter == adapters.end() ) {
958                                                // adapter has not been created yet in the current scope, so define it
959                                                FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
960                                                std::pair< AdapterIter, bool > answer = adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
961                                                adapter = answer.first;
962                                                stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
963                                        } // if
964                                        assert( adapter != adapters.end() );
965
966                                        // add the appropriate adapter as a parameter
967                                        appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
968                                } // if
969                        } // for
970                } // passAdapters
971
972                Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
973                        NameExpr *opExpr;
974                        if ( isIncr ) {
975                                opExpr = new NameExpr( "?+=?" );
976                        } else {
977                                opExpr = new NameExpr( "?-=?" );
978                        } // if
979                        UntypedExpr *addAssign = new UntypedExpr( opExpr );
980                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
981                                addAssign->get_args().push_back( address->get_arg() );
982                        } else {
983                                addAssign->get_args().push_back( appExpr->get_args().front() );
984                        } // if
985                        addAssign->get_args().push_back( new NameExpr( sizeofName( mangleType( polyType ) ) ) );
986                        addAssign->set_result( appExpr->get_result()->clone() );
987                        if ( appExpr->get_env() ) {
988                                addAssign->set_env( appExpr->get_env() );
989                                appExpr->set_env( 0 );
990                        } // if
991                        appExpr->get_args().clear();
992                        delete appExpr;
993                        return addAssign;
994                }
995
996                Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
997                        if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
998                                if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
999                                        if ( varExpr->get_var()->get_name() == "?[?]" ) {
1000                                                assert( appExpr->has_result() );
1001                                                assert( appExpr->get_args().size() == 2 );
1002                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_result(), scopeTyVars, env );
1003                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_result(), scopeTyVars, env );
1004                                                assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
1005                                                UntypedExpr *ret = 0;
1006                                                if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
1007                                                        ret = new UntypedExpr( new NameExpr( "?+?" ) );
1008                                                } // if
1009                                                if ( baseType1 ) {
1010                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1011                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1012                                                        multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1013                                                        ret->get_args().push_back( appExpr->get_args().front() );
1014                                                        ret->get_args().push_back( multiply );
1015                                                } else if ( baseType2 ) {
1016                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1017                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1018                                                        multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1019                                                        ret->get_args().push_back( multiply );
1020                                                        ret->get_args().push_back( appExpr->get_args().back() );
1021                                                } // if
1022                                                if ( baseType1 || baseType2 ) {
1023                                                        delete ret->get_result();
1024                                                        ret->set_result( appExpr->get_result()->clone() );
1025                                                        if ( appExpr->get_env() ) {
1026                                                                ret->set_env( appExpr->get_env() );
1027                                                                appExpr->set_env( 0 );
1028                                                        } // if
1029                                                        appExpr->get_args().clear();
1030                                                        delete appExpr;
1031                                                        return ret;
1032                                                } // if
1033                                        } else if ( varExpr->get_var()->get_name() == "*?" ) {
1034                                                assert( appExpr->has_result() );
1035                                                assert( ! appExpr->get_args().empty() );
1036                                                if ( isPolyType( appExpr->get_result(), scopeTyVars, env ) ) {
1037                                                        // remove dereference from polymorphic types since they are boxed.
1038                                                        Expression *ret = appExpr->get_args().front();
1039                                                        // fix expr type to remove pointer
1040                                                        delete ret->get_result();
1041                                                        ret->set_result( appExpr->get_result()->clone() );
1042                                                        if ( appExpr->get_env() ) {
1043                                                                ret->set_env( appExpr->get_env() );
1044                                                                appExpr->set_env( 0 );
1045                                                        } // if
1046                                                        appExpr->get_args().clear();
1047                                                        delete appExpr;
1048                                                        return ret;
1049                                                } // if
1050                                        } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
1051                                                assert( appExpr->has_result() );
1052                                                assert( appExpr->get_args().size() == 1 );
1053                                                if ( Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env ) ) {
1054                                                        Type *tempType = appExpr->get_result()->clone();
1055                                                        if ( env ) {
1056                                                                env->apply( tempType );
1057                                                        } // if
1058                                                        ObjectDecl *newObj = makeTemporary( tempType );
1059                                                        VariableExpr *tempExpr = new VariableExpr( newObj );
1060                                                        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
1061                                                        assignExpr->get_args().push_back( tempExpr->clone() );
1062                                                        if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
1063                                                                assignExpr->get_args().push_back( address->get_arg()->clone() );
1064                                                        } else {
1065                                                                assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
1066                                                        } // if
1067                                                        CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
1068                                                        return new CommaExpr( firstComma, tempExpr );
1069                                                } // if
1070                                        } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
1071                                                assert( appExpr->has_result() );
1072                                                assert( appExpr->get_args().size() == 1 );
1073                                                if ( Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env ) ) {
1074                                                        return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
1075                                                } // if
1076                                        } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
1077                                                assert( appExpr->has_result() );
1078                                                assert( appExpr->get_args().size() == 2 );
1079                                                Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_result(), scopeTyVars, env );
1080                                                Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_result(), scopeTyVars, env );
1081                                                if ( baseType1 && baseType2 ) {
1082                                                        UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
1083                                                        divide->get_args().push_back( appExpr );
1084                                                        divide->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1085                                                        divide->set_result( appExpr->get_result()->clone() );
1086                                                        if ( appExpr->get_env() ) {
1087                                                                divide->set_env( appExpr->get_env() );
1088                                                                appExpr->set_env( 0 );
1089                                                        } // if
1090                                                        return divide;
1091                                                } else if ( baseType1 ) {
1092                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1093                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1094                                                        multiply->get_args().push_back( new SizeofExpr( baseType1->clone() ) );
1095                                                        appExpr->get_args().back() = multiply;
1096                                                } else if ( baseType2 ) {
1097                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1098                                                        multiply->get_args().push_back( appExpr->get_args().front() );
1099                                                        multiply->get_args().push_back( new SizeofExpr( baseType2->clone() ) );
1100                                                        appExpr->get_args().front() = multiply;
1101                                                } // if
1102                                        } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
1103                                                assert( appExpr->has_result() );
1104                                                assert( appExpr->get_args().size() == 2 );
1105                                                Type *baseType = isPolyPtr( appExpr->get_result(), scopeTyVars, env );
1106                                                if ( baseType ) {
1107                                                        UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
1108                                                        multiply->get_args().push_back( appExpr->get_args().back() );
1109                                                        multiply->get_args().push_back( new SizeofExpr( baseType->clone() ) );
1110                                                        appExpr->get_args().back() = multiply;
1111                                                } // if
1112                                        } // if
1113                                        return appExpr;
1114                                } // if
1115                        } // if
1116                        return 0;
1117                }
1118
1119                Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
1120                        // std::cerr << "mutate appExpr: " << InitTweak::getFunctionName( appExpr ) << std::endl;
1121                        // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
1122                        //      std::cerr << i->first << " ";
1123                        // }
1124                        // std::cerr << "\n";
1125                        appExpr->get_function()->acceptMutator( *this );
1126                        mutateAll( appExpr->get_args(), *this );
1127
1128                        assert( appExpr->get_function()->has_result() );
1129                        FunctionType * function = getFunctionType( appExpr->get_function()->get_result() );
1130                        assertf( function, "ApplicationExpr has non-function type: %s", toString( appExpr->get_function()->get_result() ).c_str() );
1131
1132                        if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
1133                                return newExpr;
1134                        } // if
1135
1136                        Expression *ret = appExpr;
1137
1138                        std::list< Expression *>::iterator arg = appExpr->get_args().begin();
1139                        std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
1140
1141                        TyVarMap exprTyVars( TypeDecl::Data{} );
1142                        makeTyVarMap( function, exprTyVars ); // xxx - should this take into account the variables already bound in scopeTyVars (i.e. remove them from exprTyVars?)
1143                        ReferenceToType *dynRetType = isDynRet( function, exprTyVars );
1144
1145                        // std::cerr << function << std::endl;
1146                        // std::cerr << "scopeTyVars: ";
1147                        // printTyVarMap( std::cerr, scopeTyVars );
1148                        // std::cerr << "exprTyVars: ";
1149                        // printTyVarMap( std::cerr, exprTyVars );
1150                        // std::cerr << "env: " << *env << std::endl;
1151                        // std::cerr << needsAdapter( function, scopeTyVars ) << ! needsAdapter( function, exprTyVars) << std::endl;
1152
1153                        // NOTE: addDynRetParam needs to know the actual (generated) return type so it can make a temp variable, so pass the result type from the appExpr
1154                        // passTypeVars needs to know the program-text return type (i.e. the distinction between _conc_T30 and T3(int))
1155                        // concRetType may not be a good name in one or both of these places. A more appropriate name change is welcome.
1156                        if ( dynRetType ) {
1157                                // std::cerr << "dynRetType: " << dynRetType << std::endl;
1158                                Type *concRetType = appExpr->get_result()->isVoid() ? nullptr : appExpr->get_result();
1159                                ret = addDynRetParam( appExpr, concRetType, arg ); // xxx - used to use dynRetType instead of concRetType
1160                        } else if ( needsAdapter( function, scopeTyVars ) && ! needsAdapter( function, exprTyVars) ) { // xxx - exprTyVars is used above...?
1161                                // xxx - the ! needsAdapter check may be incorrect. It seems there is some situation where an adapter is applied where it shouldn't be, and this fixes it for some cases. More investigation is needed.
1162
1163                                // std::cerr << "needs adapter: ";
1164                                // printTyVarMap( std::cerr, scopeTyVars );
1165                                // std::cerr << *env << std::endl;
1166                                // change the application so it calls the adapter rather than the passed function
1167                                ret = applyAdapter( appExpr, function, arg, scopeTyVars );
1168                        } // if
1169                        arg = appExpr->get_args().begin();
1170
1171                        Type *concRetType = replaceWithConcrete( appExpr, dynRetType );
1172                        passTypeVars( appExpr, concRetType, arg, exprTyVars ); // xxx - used to use dynRetType instead of concRetType; this changed so that the correct type paramaters are passed for return types (it should be the concrete type's parameters, not the formal type's)
1173                        addInferredParams( appExpr, function, arg, exprTyVars );
1174
1175                        arg = paramBegin;
1176
1177                        boxParams( appExpr, function, arg, exprTyVars );
1178                        passAdapters( appExpr, function, exprTyVars );
1179
1180                        return ret;
1181                }
1182
1183                Expression *Pass1::mutate( UntypedExpr *expr ) {
1184                        if ( expr->has_result() && isPolyType( expr->get_result(), scopeTyVars, env ) ) {
1185                                if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1186                                        if ( name->get_name() == "*?" ) {
1187                                                Expression *ret = expr->get_args().front();
1188                                                expr->get_args().clear();
1189                                                delete expr;
1190                                                return ret->acceptMutator( *this );
1191                                        } // if
1192                                } // if
1193                        } // if
1194                        return PolyMutator::mutate( expr );
1195                }
1196
1197                Expression *Pass1::mutate( AddressExpr *addrExpr ) {
1198                        assert( addrExpr->get_arg()->has_result() && ! addrExpr->get_arg()->get_result()->isVoid() );
1199
1200                        bool needs = false;
1201                        if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
1202                                if ( expr->has_result() && isPolyType( expr->get_result(), scopeTyVars, env ) ) {
1203                                        if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
1204                                                if ( name->get_name() == "*?" ) {
1205                                                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
1206                                                                assert( appExpr->get_function()->has_result() );
1207                                                                FunctionType *function = getFunctionType( appExpr->get_function()->get_result() );
1208                                                                assert( function );
1209                                                                needs = needsAdapter( function, scopeTyVars );
1210                                                        } // if
1211                                                } // if
1212                                        } // if
1213                                } // if
1214                        } // if
1215                        // isPolyType check needs to happen before mutating addrExpr arg, so pull it forward
1216                        // out of the if condition.
1217                        addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
1218                        // ... but must happen after mutate, since argument might change (e.g. intrinsic *?, ?[?]) - re-evaluate above comment
1219                        bool polytype = isPolyType( addrExpr->get_arg()->get_result(), scopeTyVars, env );
1220                        if ( polytype || needs ) {
1221                                Expression *ret = addrExpr->get_arg();
1222                                delete ret->get_result();
1223                                ret->set_result( addrExpr->get_result()->clone() );
1224                                addrExpr->set_arg( 0 );
1225                                delete addrExpr;
1226                                return ret;
1227                        } else {
1228                                return addrExpr;
1229                        } // if
1230                }
1231
1232                Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1233                        if ( retval && returnStmt->get_expr() ) {
1234                                assert( returnStmt->get_expr()->has_result() && ! returnStmt->get_expr()->get_result()->isVoid() );
1235                                delete returnStmt->get_expr();
1236                                returnStmt->set_expr( 0 );
1237                        } else {
1238                                returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
1239                        } // if
1240                        return returnStmt;
1241                }
1242
1243                Type * Pass1::mutate( PointerType *pointerType ) {
1244                        scopeTyVars.beginScope();
1245                        makeTyVarMap( pointerType, scopeTyVars );
1246
1247                        Type *ret = Mutator::mutate( pointerType );
1248
1249                        scopeTyVars.endScope();
1250                        return ret;
1251                }
1252
1253                Type * Pass1::mutate( FunctionType *functionType ) {
1254                        scopeTyVars.beginScope();
1255                        makeTyVarMap( functionType, scopeTyVars );
1256
1257                        Type *ret = Mutator::mutate( functionType );
1258
1259                        scopeTyVars.endScope();
1260                        return ret;
1261                }
1262
1263                void Pass1::doBeginScope() {
1264                        adapters.beginScope();
1265                }
1266
1267                void Pass1::doEndScope() {
1268                        adapters.endScope();
1269                }
1270
1271////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1272
1273                void Pass2::addAdapters( FunctionType *functionType ) {
1274                        std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1275                        std::list< FunctionType *> functions;
1276                        for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1277                                Type *orig = (*arg)->get_type();
1278                                findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1279                                (*arg)->set_type( orig );
1280                        }
1281                        std::set< std::string > adaptersDone;
1282                        for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
1283                                std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
1284                                if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1285                                        std::string adapterName = makeAdapterName( mangleName );
1286                                        // adapter may not be used in body, pass along with unused attribute.
1287                                        paramList.push_front( new ObjectDecl( adapterName, Type::StorageClasses(), LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0, { new Attribute( "unused" ) } ) );
1288                                        adaptersDone.insert( adaptersDone.begin(), mangleName );
1289                                }
1290                        }
1291//  deleteAll( functions );
1292                }
1293
1294                template< typename DeclClass >
1295                DeclClass * Pass2::handleDecl( DeclClass *decl ) {
1296                        DeclClass *ret = static_cast< DeclClass *>( Parent::mutate( decl ) );
1297
1298                        return ret;
1299                }
1300
1301                DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1302                        functionDecl = strict_dynamic_cast< FunctionDecl * > ( handleDecl( functionDecl ) );
1303                        FunctionType * ftype = functionDecl->get_functionType();
1304                        if ( ! ftype->get_returnVals().empty() && functionDecl->get_statements() ) {
1305                                if ( ! isPrefix( functionDecl->get_name(), "_thunk" ) && ! isPrefix( functionDecl->get_name(), "_adapter" ) ) { // xxx - remove check for prefix once thunks properly use ctor/dtors
1306                                        assert( ftype->get_returnVals().size() == 1 );
1307                                        DeclarationWithType * retval = ftype->get_returnVals().front();
1308                                        if ( retval->get_name() == "" ) {
1309                                                retval->set_name( "_retval" );
1310                                        }
1311                                        functionDecl->get_statements()->get_kids().push_front( new DeclStmt( noLabels, retval ) );
1312                                        DeclarationWithType * newRet = retval->clone(); // for ownership purposes
1313                                        ftype->get_returnVals().front() = newRet;
1314                                }
1315                        }
1316                        // errors should have been caught by this point, remove initializers from parameters to allow correct codegen of default arguments
1317                        for ( Declaration * param : functionDecl->get_functionType()->get_parameters() ) {
1318                                if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( param ) ) {
1319                                        delete obj->get_init();
1320                                        obj->set_init( nullptr );
1321                                }
1322                        }
1323                        return functionDecl;
1324                }
1325
1326                ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1327                        return handleDecl( objectDecl );
1328                }
1329
1330                template< typename AggDecl >
1331                AggDecl * Pass2::handleAggDecl( AggDecl * aggDecl ) {
1332                        // prevent tyVars from leaking into containing scope
1333                        scopeTyVars.beginScope();
1334                        Parent::mutate( aggDecl );
1335                        scopeTyVars.endScope();
1336                        return aggDecl;
1337                }
1338
1339                StructDecl * Pass2::mutate( StructDecl *aggDecl ) {
1340                        return handleAggDecl( aggDecl );
1341                }
1342
1343                UnionDecl * Pass2::mutate( UnionDecl *aggDecl ) {
1344                        return handleAggDecl( aggDecl );
1345                }
1346
1347                TraitDecl * Pass2::mutate( TraitDecl *aggDecl ) {
1348                        return handleAggDecl( aggDecl );
1349                }
1350
1351                TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1352                        addToTyVarMap( typeDecl, scopeTyVars );
1353                        if ( typeDecl->get_base() ) {
1354                                return handleDecl( typeDecl );
1355                        } else {
1356                                return dynamic_cast<TypeDecl*>( Parent::mutate( typeDecl ) );
1357                        }
1358                }
1359
1360                TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1361                        return handleDecl( typedefDecl );
1362                }
1363
1364                Type * Pass2::mutate( PointerType *pointerType ) {
1365                        scopeTyVars.beginScope();
1366                        makeTyVarMap( pointerType, scopeTyVars );
1367
1368                        Type *ret = Parent::mutate( pointerType );
1369
1370                        scopeTyVars.endScope();
1371                        return ret;
1372                }
1373
1374                Type *Pass2::mutate( FunctionType *funcType ) {
1375                        scopeTyVars.beginScope();
1376
1377                        makeTyVarMap( funcType, scopeTyVars );
1378
1379                        // move polymorphic return type to parameter list
1380                        if ( isDynRet( funcType ) ) {
1381                                ObjectDecl *ret = strict_dynamic_cast< ObjectDecl* >( funcType->get_returnVals().front() );
1382                                ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1383                                funcType->get_parameters().push_front( ret );
1384                                funcType->get_returnVals().pop_front();
1385                                ret->set_init( nullptr ); // xxx - memory leak?
1386                        }
1387
1388                        // add size/align and assertions for type parameters to parameter list
1389                        std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1390                        std::list< DeclarationWithType *> inferredParams;
1391                        // size/align/offset parameters may not be used in body, pass along with unused attribute.
1392                        ObjectDecl newObj( "", Type::StorageClasses(), LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0,
1393                                           { new Attribute( "unused" ) } );
1394                        ObjectDecl newPtr( "", Type::StorageClasses(), LinkageSpec::C, 0,
1395                                           new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
1396                        for ( Type::ForallList::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
1397                                ObjectDecl *sizeParm, *alignParm;
1398                                // add all size and alignment parameters to parameter list
1399                                if ( (*tyParm)->isComplete() ) {
1400                                        TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
1401                                        std::string parmName = mangleType( &parmType );
1402
1403                                        sizeParm = newObj.clone();
1404                                        sizeParm->set_name( sizeofName( parmName ) );
1405                                        last = funcType->get_parameters().insert( last, sizeParm );
1406                                        ++last;
1407
1408                                        alignParm = newObj.clone();
1409                                        alignParm->set_name( alignofName( parmName ) );
1410                                        last = funcType->get_parameters().insert( last, alignParm );
1411                                        ++last;
1412                                }
1413                                // move all assertions into parameter list
1414                                for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
1415//      *assert = (*assert)->acceptMutator( *this );
1416                                        // assertion parameters may not be used in body, pass along with unused attribute.
1417                                        (*assert)->get_attributes().push_back( new Attribute( "unused" ) );
1418                                        inferredParams.push_back( *assert );
1419                                }
1420                                (*tyParm)->get_assertions().clear();
1421                        }
1422
1423                        // add size/align for generic parameter types to parameter list
1424                        std::set< std::string > seenTypes; // sizeofName for generic types we've seen
1425                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
1426                                Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1427                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1428                                        std::string typeName = mangleType( polyType );
1429                                        if ( seenTypes.count( typeName ) ) continue;
1430
1431                                        ObjectDecl *sizeParm, *alignParm, *offsetParm;
1432                                        sizeParm = newObj.clone();
1433                                        sizeParm->set_name( sizeofName( typeName ) );
1434                                        last = funcType->get_parameters().insert( last, sizeParm );
1435                                        ++last;
1436
1437                                        alignParm = newObj.clone();
1438                                        alignParm->set_name( alignofName( typeName ) );
1439                                        last = funcType->get_parameters().insert( last, alignParm );
1440                                        ++last;
1441
1442                                        if ( StructInstType *polyBaseStruct = dynamic_cast< StructInstType* >( polyType ) ) {
1443                                                // NOTE zero-length arrays are illegal in C, so empty structs have no offset array
1444                                                if ( ! polyBaseStruct->get_baseStruct()->get_members().empty() ) {
1445                                                        offsetParm = newPtr.clone();
1446                                                        offsetParm->set_name( offsetofName( typeName ) );
1447                                                        last = funcType->get_parameters().insert( last, offsetParm );
1448                                                        ++last;
1449                                                }
1450                                        }
1451
1452                                        seenTypes.insert( typeName );
1453                                }
1454                        }
1455
1456                        // splice assertion parameters into parameter list
1457                        funcType->get_parameters().splice( last, inferredParams );
1458                        addAdapters( funcType );
1459                        mutateAll( funcType->get_returnVals(), *this );
1460                        mutateAll( funcType->get_parameters(), *this );
1461
1462                        scopeTyVars.endScope();
1463                        return funcType;
1464                }
1465
1466////////////////////////////////////////// PolyGenericCalculator ////////////////////////////////////////////////////
1467
1468                PolyGenericCalculator::PolyGenericCalculator()
1469                        : knownLayouts(), knownOffsets(), bufNamer( "_buf" ), scopeTyVars( TypeDecl::Data{} ) {}
1470
1471                void PolyGenericCalculator::beginTypeScope( Type *ty ) {
1472                        GuardScope( scopeTyVars );
1473                        makeTyVarMap( ty, scopeTyVars );
1474                }
1475
1476                void PolyGenericCalculator::beginGenericScope() {
1477                        GuardScope( *this );
1478                }
1479
1480                void PolyGenericCalculator::premutate( ObjectDecl *objectDecl ) {
1481                        beginTypeScope( objectDecl->get_type() );
1482                }
1483
1484                void PolyGenericCalculator::premutate( FunctionDecl *functionDecl ) {
1485                        beginGenericScope();
1486
1487                        beginTypeScope( functionDecl->get_functionType() );
1488                }
1489
1490                void PolyGenericCalculator::premutate( TypedefDecl *typedefDecl ) {
1491                        beginTypeScope( typedefDecl->get_base() );
1492                }
1493
1494                void PolyGenericCalculator::premutate( TypeDecl * typeDecl ) {
1495                        addToTyVarMap( typeDecl, scopeTyVars );
1496                }
1497
1498                Declaration * PolyGenericCalculator::postmutate( TypeDecl *typeDecl ) {
1499                        if ( Type * base = typeDecl->base ) {
1500                                // add size/align variables for opaque type declarations
1501                                TypeInstType inst( Type::Qualifiers(), typeDecl->name, typeDecl );
1502                                std::string typeName = mangleType( &inst );
1503                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1504
1505                                ObjectDecl * sizeDecl = ObjectDecl::newObject( sizeofName( typeName ), layoutType, new SingleInit( new SizeofExpr( base->clone() ) ) );
1506                                ObjectDecl * alignDecl = ObjectDecl::newObject( alignofName( typeName ), layoutType->clone(), new SingleInit( new AlignofExpr( base->clone() ) ) );
1507
1508                                // ensure that the initializing sizeof/alignof exprs are properly mutated
1509                                sizeDecl->acceptMutator( *visitor );
1510                                alignDecl->acceptMutator( *visitor );
1511
1512                                // can't use makeVar, because it inserts into stmtsToAdd and TypeDecls can occur at global scope
1513                                declsToAddAfter.push_back( alignDecl );
1514                                // replace with sizeDecl
1515                                return sizeDecl;
1516                        }
1517                        return typeDecl;
1518                }
1519
1520                void PolyGenericCalculator::premutate( PointerType *pointerType ) {
1521                        beginTypeScope( pointerType );
1522                }
1523
1524                void PolyGenericCalculator::premutate( FunctionType *funcType ) {
1525                        beginTypeScope( funcType );
1526
1527                        // make sure that any type information passed into the function is accounted for
1528                        for ( std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin(); fnParm != funcType->get_parameters().end(); ++fnParm ) {
1529                                // condition here duplicates that in Pass2::mutate( FunctionType* )
1530                                Type *polyType = isPolyType( (*fnParm)->get_type(), scopeTyVars );
1531                                if ( polyType && ! dynamic_cast< TypeInstType* >( polyType ) ) {
1532                                        knownLayouts.insert( mangleType( polyType ) );
1533                                }
1534                        }
1535                }
1536
1537                void PolyGenericCalculator::premutate( DeclStmt *declStmt ) {
1538                        if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
1539                                if ( findGeneric( objectDecl->get_type() ) ) {
1540                                        // change initialization of a polymorphic value object to allocate via a VLA
1541                                        // (alloca was previously used, but can't be safely used in loops)
1542                                        Type *declType = objectDecl->get_type();
1543                                        ObjectDecl *newBuf = new ObjectDecl( bufNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0,
1544                                                new ArrayType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::Kind::Char), new NameExpr( sizeofName( mangleType(declType) ) ),
1545                                                true, false, std::list<Attribute*>{ new Attribute( "aligned", std::list<Expression*>{ new ConstantExpr( Constant::from_int(8) ) } ) } ), 0 );
1546                                        stmtsToAddBefore.push_back( new DeclStmt( noLabels, newBuf ) );
1547
1548                                        delete objectDecl->get_init();
1549                                        objectDecl->set_init( new SingleInit( new VariableExpr( newBuf ) ) );
1550                                }
1551                        }
1552                }
1553
1554                /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1555                long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1556                        long i = 0;
1557                        for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1558                                if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1559
1560                                if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
1561                                        if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1562                                             || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
1563                                        else continue;
1564                                } else return i;
1565                        }
1566                        return -1;
1567                }
1568
1569                /// Returns an index expression into the offset array for a type
1570                Expression *makeOffsetIndex( Type *objectType, long i ) {
1571                        ConstantExpr *fieldIndex = new ConstantExpr( Constant::from_ulong( i ) );
1572                        UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1573                        fieldOffset->get_args().push_back( new NameExpr( offsetofName( mangleType( objectType ) ) ) );
1574                        fieldOffset->get_args().push_back( fieldIndex );
1575                        return fieldOffset;
1576                }
1577
1578                Expression *PolyGenericCalculator::postmutate( MemberExpr *memberExpr ) {
1579                        // only mutate member expressions for polymorphic types
1580                        int tyDepth;
1581                        Type *objectType = hasPolyBase( memberExpr->get_aggregate()->get_result(), scopeTyVars, &tyDepth );
1582                        if ( ! objectType ) return memberExpr;
1583                        findGeneric( objectType ); // ensure layout for this type is available
1584
1585                        // replace member expression with dynamically-computed layout expression
1586                        Expression *newMemberExpr = 0;
1587                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
1588                                // look up offset index
1589                                long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1590                                if ( i == -1 ) return memberExpr;
1591
1592                                // replace member expression with pointer to base plus offset
1593                                UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1594                                Expression * aggr = memberExpr->get_aggregate()->clone();
1595                                delete aggr->get_env(); // xxx - there's a problem with keeping the env for some reason, so for now just get rid of it
1596                                aggr->set_env( nullptr );
1597                                fieldLoc->get_args().push_back( aggr );
1598                                fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
1599                                fieldLoc->set_result( memberExpr->get_result()->clone() );
1600                                newMemberExpr = fieldLoc;
1601                        } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
1602                                // union members are all at offset zero, so just use the aggregate expr
1603                                Expression * aggr = memberExpr->get_aggregate()->clone();
1604                                delete aggr->get_env(); // xxx - there's a problem with keeping the env for some reason, so for now just get rid of it
1605                                aggr->set_env( nullptr );
1606                                newMemberExpr = aggr;
1607                                newMemberExpr->set_result( memberExpr->get_result()->clone() );
1608                        } else return memberExpr;
1609                        assert( newMemberExpr );
1610
1611                        Type *memberType = memberExpr->get_member()->get_type();
1612                        if ( ! isPolyType( memberType, scopeTyVars ) ) {
1613                                // 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
1614                                CastExpr *ptrCastExpr = new CastExpr( newMemberExpr, new PointerType( Type::Qualifiers(), memberType->clone() ) );
1615                                UntypedExpr *derefExpr = UntypedExpr::createDeref( ptrCastExpr );
1616                                newMemberExpr = derefExpr;
1617                        }
1618
1619                        delete memberExpr;
1620                        return newMemberExpr;
1621                }
1622
1623                ObjectDecl *PolyGenericCalculator::makeVar( const std::string &name, Type *type, Initializer *init ) {
1624                        ObjectDecl *newObj = new ObjectDecl( name, Type::StorageClasses(), LinkageSpec::C, 0, type, init );
1625                        stmtsToAddBefore.push_back( new DeclStmt( noLabels, newObj ) );
1626                        return newObj;
1627                }
1628
1629                void PolyGenericCalculator::addOtypeParamsToLayoutCall( UntypedExpr *layoutCall, const std::list< Type* > &otypeParams ) {
1630                        for ( std::list< Type* >::const_iterator param = otypeParams.begin(); param != otypeParams.end(); ++param ) {
1631                                if ( findGeneric( *param ) ) {
1632                                        // push size/align vars for a generic parameter back
1633                                        std::string paramName = mangleType( *param );
1634                                        layoutCall->get_args().push_back( new NameExpr( sizeofName( paramName ) ) );
1635                                        layoutCall->get_args().push_back( new NameExpr( alignofName( paramName ) ) );
1636                                } else {
1637                                        layoutCall->get_args().push_back( new SizeofExpr( (*param)->clone() ) );
1638                                        layoutCall->get_args().push_back( new AlignofExpr( (*param)->clone() ) );
1639                                }
1640                        }
1641                }
1642
1643                /// returns true if any of the otype parameters have a dynamic layout and puts all otype parameters in the output list
1644                bool findGenericParams( std::list< TypeDecl* > &baseParams, std::list< Expression* > &typeParams, std::list< Type* > &out ) {
1645                        bool hasDynamicLayout = false;
1646
1647                        std::list< TypeDecl* >::const_iterator baseParam = baseParams.begin();
1648                        std::list< Expression* >::const_iterator typeParam = typeParams.begin();
1649                        for ( ; baseParam != baseParams.end() && typeParam != typeParams.end(); ++baseParam, ++typeParam ) {
1650                                // skip non-otype parameters
1651                                if ( ! (*baseParam)->isComplete() ) continue;
1652                                TypeExpr *typeExpr = dynamic_cast< TypeExpr* >( *typeParam );
1653                                assert( typeExpr && "all otype parameters should be type expressions" );
1654
1655                                Type *type = typeExpr->get_type();
1656                                out.push_back( type );
1657                                if ( isPolyType( type ) ) hasDynamicLayout = true;
1658                        }
1659                        assert( baseParam == baseParams.end() && typeParam == typeParams.end() );
1660
1661                        return hasDynamicLayout;
1662                }
1663
1664                bool PolyGenericCalculator::findGeneric( Type *ty ) {
1665                        ty = replaceTypeInst( ty, env );
1666
1667                        if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( ty ) ) {
1668                                if ( scopeTyVars.find( typeInst->get_name() ) != scopeTyVars.end() ) {
1669                                        // NOTE assumes here that getting put in the scopeTyVars included having the layout variables set
1670                                        return true;
1671                                }
1672                                return false;
1673                        } else if ( StructInstType *structTy = dynamic_cast< StructInstType* >( ty ) ) {
1674                                // check if this type already has a layout generated for it
1675                                std::string typeName = mangleType( ty );
1676                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1677
1678                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1679                                std::list< Type* > otypeParams;
1680                                if ( ! findGenericParams( *structTy->get_baseParameters(), structTy->get_parameters(), otypeParams ) ) return false;
1681
1682                                // insert local variables for layout and generate call to layout function
1683                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1684                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1685
1686                                int n_members = structTy->get_baseStruct()->get_members().size();
1687                                if ( n_members == 0 ) {
1688                                        // all empty structs have the same layout - size 1, align 1
1689                                        makeVar( sizeofName( typeName ), layoutType, new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1690                                        makeVar( alignofName( typeName ), layoutType->clone(), new SingleInit( new ConstantExpr( Constant::from_ulong( (unsigned long)1 ) ) ) );
1691                                        // NOTE zero-length arrays are forbidden in C, so empty structs have no offsetof array
1692                                } else {
1693                                        ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1694                                        ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1695                                        ObjectDecl *offsetVar = makeVar( offsetofName( typeName ), new ArrayType( Type::Qualifiers(), layoutType->clone(), new ConstantExpr( Constant::from_int( n_members ) ), false, false ) );
1696
1697                                        // generate call to layout function
1698                                        UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( structTy->get_baseStruct() ) ) );
1699                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1700                                        layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1701                                        layoutCall->get_args().push_back( new VariableExpr( offsetVar ) );
1702                                        addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1703
1704                                        stmtsToAddBefore.push_back( new ExprStmt( noLabels, layoutCall ) );
1705                                }
1706
1707                                return true;
1708                        } else if ( UnionInstType *unionTy = dynamic_cast< UnionInstType* >( ty ) ) {
1709                                // check if this type already has a layout generated for it
1710                                std::string typeName = mangleType( ty );
1711                                if ( knownLayouts.find( typeName ) != knownLayouts.end() ) return true;
1712
1713                                // check if any of the type parameters have dynamic layout; if none do, this type is (or will be) monomorphized
1714                                std::list< Type* > otypeParams;
1715                                if ( ! findGenericParams( *unionTy->get_baseParameters(), unionTy->get_parameters(), otypeParams ) ) return false;
1716
1717                                // insert local variables for layout and generate call to layout function
1718                                knownLayouts.insert( typeName );  // done early so as not to interfere with the later addition of parameters to the layout call
1719                                Type *layoutType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1720
1721                                ObjectDecl *sizeVar = makeVar( sizeofName( typeName ), layoutType );
1722                                ObjectDecl *alignVar = makeVar( alignofName( typeName ), layoutType->clone() );
1723
1724                                // generate call to layout function
1725                                UntypedExpr *layoutCall = new UntypedExpr( new NameExpr( layoutofName( unionTy->get_baseUnion() ) ) );
1726                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( sizeVar ) ) );
1727                                layoutCall->get_args().push_back( new AddressExpr( new VariableExpr( alignVar ) ) );
1728                                addOtypeParamsToLayoutCall( layoutCall, otypeParams );
1729
1730                                stmtsToAddBefore.push_back( new ExprStmt( noLabels, layoutCall ) );
1731
1732                                return true;
1733                        }
1734
1735                        return false;
1736                }
1737
1738                Expression *PolyGenericCalculator::postmutate( SizeofExpr *sizeofExpr ) {
1739                        Type *ty = sizeofExpr->get_isType() ? sizeofExpr->get_type() : sizeofExpr->get_expr()->get_result();
1740                        if ( findGeneric( ty ) ) {
1741                                Expression *ret = new NameExpr( sizeofName( mangleType( ty ) ) );
1742                                delete sizeofExpr;
1743                                return ret;
1744                        }
1745                        return sizeofExpr;
1746                }
1747
1748                Expression *PolyGenericCalculator::postmutate( AlignofExpr *alignofExpr ) {
1749                        Type *ty = alignofExpr->get_isType() ? alignofExpr->get_type() : alignofExpr->get_expr()->get_result();
1750                        if ( findGeneric( ty ) ) {
1751                                Expression *ret = new NameExpr( alignofName( mangleType( ty ) ) );
1752                                delete alignofExpr;
1753                                return ret;
1754                        }
1755                        return alignofExpr;
1756                }
1757
1758                Expression *PolyGenericCalculator::postmutate( OffsetofExpr *offsetofExpr ) {
1759                        // only mutate expressions for polymorphic structs/unions
1760                        Type *ty = offsetofExpr->get_type();
1761                        if ( ! findGeneric( ty ) ) return offsetofExpr;
1762
1763                        if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1764                                // replace offsetof expression by index into offset array
1765                                long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1766                                if ( i == -1 ) return offsetofExpr;
1767
1768                                Expression *offsetInd = makeOffsetIndex( ty, i );
1769                                delete offsetofExpr;
1770                                return offsetInd;
1771                        } else if ( dynamic_cast< UnionInstType* >( ty ) ) {
1772                                // all union members are at offset zero
1773                                delete offsetofExpr;
1774                                return new ConstantExpr( Constant::from_ulong( 0 ) );
1775                        } else return offsetofExpr;
1776                }
1777
1778                Expression *PolyGenericCalculator::postmutate( OffsetPackExpr *offsetPackExpr ) {
1779                        StructInstType *ty = offsetPackExpr->get_type();
1780
1781                        Expression *ret = 0;
1782                        if ( findGeneric( ty ) ) {
1783                                // pull offset back from generated type information
1784                                ret = new NameExpr( offsetofName( mangleType( ty ) ) );
1785                        } else {
1786                                std::string offsetName = offsetofName( mangleType( ty ) );
1787                                if ( knownOffsets.find( offsetName ) != knownOffsets.end() ) {
1788                                        // use the already-generated offsets for this type
1789                                        ret = new NameExpr( offsetName );
1790                                } else {
1791                                        knownOffsets.insert( offsetName );
1792
1793                                        std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
1794                                        Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
1795
1796                                        // build initializer list for offset array
1797                                        std::list< Initializer* > inits;
1798                                        for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
1799                                                if ( DeclarationWithType *memberDecl = dynamic_cast< DeclarationWithType* >( *member ) ) {
1800                                                        inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
1801                                                } else {
1802                                                        assertf( false, "Requesting offset of Non-DWT member: %s", toString( *member ).c_str() );
1803                                                }
1804                                        }
1805
1806                                        // build the offset array and replace the pack with a reference to it
1807                                        ObjectDecl *offsetArray = makeVar( offsetName, new ArrayType( Type::Qualifiers(), offsetType, new ConstantExpr( Constant::from_ulong( baseMembers.size() ) ), false, false ),
1808                                                        new ListInit( inits ) );
1809                                        ret = new VariableExpr( offsetArray );
1810                                }
1811                        }
1812
1813                        delete offsetPackExpr;
1814                        return ret;
1815                }
1816
1817                void PolyGenericCalculator::beginScope() {
1818                        knownLayouts.beginScope();
1819                        knownOffsets.beginScope();
1820                }
1821
1822                void PolyGenericCalculator::endScope() {
1823                        knownLayouts.endScope();
1824                        knownOffsets.endScope();
1825                }
1826
1827////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1828
1829                template< typename DeclClass >
1830                void Pass3::handleDecl( DeclClass * decl, Type * type ) {
1831                        GuardScope( scopeTyVars );
1832                        makeTyVarMap( type, scopeTyVars );
1833                        ScrubTyVars::scrubAll( decl );
1834                }
1835
1836                void Pass3::premutate( ObjectDecl * objectDecl ) {
1837                        handleDecl( objectDecl, objectDecl->type );
1838                }
1839
1840                void Pass3::premutate( FunctionDecl * functionDecl ) {
1841                        handleDecl( functionDecl, functionDecl->type );
1842                }
1843
1844                void Pass3::premutate( TypedefDecl * typedefDecl ) {
1845                        handleDecl( typedefDecl, typedefDecl->base );
1846                }
1847
1848                /// Strips the members from a generic aggregate
1849                void stripGenericMembers(AggregateDecl * decl) {
1850                        if ( ! decl->parameters.empty() ) decl->members.clear();
1851                }
1852
1853                void Pass3::premutate( StructDecl * structDecl ) {
1854                        stripGenericMembers( structDecl );
1855                }
1856
1857                void Pass3::premutate( UnionDecl * unionDecl ) {
1858                        stripGenericMembers( unionDecl );
1859                }
1860
1861                void Pass3::premutate( TypeDecl * typeDecl ) {
1862                        addToTyVarMap( typeDecl, scopeTyVars );
1863                }
1864
1865                void Pass3::premutate( PointerType * pointerType ) {
1866                        GuardScope( scopeTyVars );
1867                        makeTyVarMap( pointerType, scopeTyVars );
1868                }
1869
1870                void Pass3::premutate( FunctionType * functionType ) {
1871                        GuardScope( scopeTyVars );
1872                        makeTyVarMap( functionType, scopeTyVars );
1873                }
1874        } // anonymous namespace
1875} // namespace GenPoly
1876
1877// Local Variables: //
1878// tab-width: 4 //
1879// mode: c++ //
1880// compile-command: "make install" //
1881// End: //
Note: See TracBrowser for help on using the repository browser.