source: src/SymTab/Autogen.cc @ 4e06c1e

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4e06c1e was 4e06c1e, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

changes for switch and choose statements

  • Property mode set to 100644
File size: 28.6 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// Autogen.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Mar 03 15:45:56 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:47:17 2016
13// Update Count     : 2
14//
15
16#include <list>
17#include <iterator>
18#include "SynTree/Visitor.h"
19#include "SynTree/Type.h"
20#include "SynTree/Statement.h"
21#include "SynTree/TypeSubstitution.h"
22#include "Common/utility.h"
23#include "AddVisit.h"
24#include "MakeLibCfa.h"
25#include "Autogen.h"
26
27namespace SymTab {
28        class AutogenerateRoutines : public Visitor {
29                public:
30                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
31
32                virtual void visit( EnumDecl *enumDecl );
33                virtual void visit( StructDecl *structDecl );
34                virtual void visit( UnionDecl *structDecl );
35                virtual void visit( TypeDecl *typeDecl );
36                virtual void visit( TraitDecl *ctxDecl );
37                virtual void visit( FunctionDecl *functionDecl );
38
39                virtual void visit( FunctionType *ftype );
40                virtual void visit( PointerType *ftype );
41
42                virtual void visit( CompoundStmt *compoundStmt );
43                virtual void visit( SwitchStmt *switchStmt );
44
45                AutogenerateRoutines() : functionNesting( 0 ) {}
46                private:
47                template< typename StmtClass > void visitStatement( StmtClass *stmt );
48
49                std::list< Declaration * > declsToAdd;
50                std::set< std::string > structsDone;
51                unsigned int functionNesting;     // current level of nested functions
52        };
53
54        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
55                AutogenerateRoutines visitor;
56                acceptAndAdd( translationUnit, visitor, false );
57        }
58
59        bool isUnnamedBitfield( ObjectDecl * obj ) {
60                return obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL;
61        }
62
63        template< typename OutputIterator >
64        void makeScalarFunction( Expression *src, ObjectDecl *dstParam, DeclarationWithType *member, std::string fname, OutputIterator out ) {
65                ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
66                // unnamed bit fields are not copied as they cannot be accessed
67                if ( isUnnamedBitfield( obj ) ) return;
68
69                // want to be able to generate assignment, ctor, and dtor generically,
70                // so fname is either ?=?, ?{}, or ^?{}
71                UntypedExpr *fExpr = new UntypedExpr( new NameExpr( fname ) );
72
73                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
74                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
75
76                // do something special for unnamed members
77                Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
78                fExpr->get_args().push_back( dstselect );
79
80                if ( src ) {
81                        fExpr->get_args().push_back( src );
82                }
83
84                *out++ = new ExprStmt( noLabels, fExpr );
85        }
86
87        template< typename OutputIterator >
88        void makeUnionFieldsAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, UnionInstType *unionType, OutputIterator out ) {
89                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
90                copy->get_args().push_back( new VariableExpr( dstParam ) );
91                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
92                copy->get_args().push_back( new SizeofExpr( unionType ) );
93
94                *out++ = new ExprStmt( noLabels, copy );
95        }
96
97        //E ?=?(E volatile*, int),
98        //  ?=?(E _Atomic volatile*, int);
99        void makeEnumFunctions( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
100                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
101
102                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType ), 0 );
103                assignType->get_parameters().push_back( dstParam );
104
105                // void ?{}(E *); void ^?{}(E *);
106                FunctionType * ctorType = assignType->clone();
107                FunctionType * dtorType = assignType->clone();
108
109                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
110                assignType->get_parameters().push_back( srcParam );
111                // void ?{}(E *, E);
112                FunctionType *copyCtorType = assignType->clone();
113
114                // T ?=?(E *, E);
115                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
116                assignType->get_returnVals().push_back( returnVal );
117
118                // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
119                // right now these cases work, but that might change.
120
121                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
122                // because each unit generates copies of the default routines for each aggregate.
123                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
124                // Really they're something of a cross between instrinsic and autogen, so should
125                // probably make a new linkage type
126                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, new CompoundStmt( noLabels ), true, false );
127                FunctionDecl *ctorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, ctorType, new CompoundStmt( noLabels ), true, false );
128                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, copyCtorType, new CompoundStmt( noLabels ), true, false );
129                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, dtorType, new CompoundStmt( noLabels ), true, false );
130                assignDecl->fixUniqueId();
131                ctorDecl->fixUniqueId();
132                copyCtorDecl->fixUniqueId();
133                dtorDecl->fixUniqueId();
134
135                // enum copy construct and assignment is just C-style assignment.
136                // this looks like a bad recursive call, but code gen will turn it into
137                // a C-style assignment.
138                // This happens before function pointer type conversion, so need to do it manually here
139                VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
140                Type *& assignVarExprType = assignVarExpr->get_results().front();
141                assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
142                ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
143                assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
144                assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
145
146                // body is either return stmt or expr stmt
147                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, assignExpr ) );
148                copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, assignExpr->clone() ) );
149
150                declsToAdd.push_back( assignDecl );
151                declsToAdd.push_back( ctorDecl );
152                declsToAdd.push_back( copyCtorDecl );
153                declsToAdd.push_back( dtorDecl );
154        }
155
156        /// Clones a reference type, replacing any parameters it may have with a clone of the provided list
157        template< typename GenericInstType >
158        GenericInstType *cloneWithParams( GenericInstType *refType, const std::list< Expression* >& params ) {
159                GenericInstType *clone = refType->clone();
160                clone->get_parameters().clear();
161                cloneAll( params, clone->get_parameters() );
162                return clone;
163        }
164
165        /// Creates a new type decl that's the same as src, but renamed and with only the ?=?, ?{} (default and copy), and ^?{} assertions (for complete types only)
166        TypeDecl *cloneAndRename( TypeDecl *src, const std::string &name ) {
167                // TypeDecl *dst = new TypeDecl( name, src->get_storageClass(), 0, src->get_kind() );
168
169                // if ( src->get_kind() == TypeDecl::Any ) {
170                //      TypeInstType *opParamType = new TypeInstType( Type::Qualifiers(), name, dst );
171                //      FunctionType *opFunctionType = new FunctionType( Type::Qualifiers(), false );
172                //      opFunctionType->get_parameters().push_back(
173                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), opParamType->clone() ), 0 ) );
174                //      FunctionDecl *ctorAssert = new FunctionDecl( "?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
175                //      FunctionDecl *dtorAssert = new FunctionDecl( "^?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
176
177                //      opFunctionType->get_parameters().push_back(
178                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, opParamType, 0 ) );
179                //      FunctionDecl *copyCtorAssert = new FunctionDecl( "?{}", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType->clone(), 0, false, false );
180
181                //      opFunctionType->get_returnVals().push_back(
182                //              new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, opParamType->clone(), 0 ) );
183                //      FunctionDecl *assignAssert = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, opFunctionType, 0, false, false );
184
185
186                //      dst->get_assertions().push_back( assignAssert );
187                //      dst->get_assertions().push_back( ctorAssert );
188                //      dst->get_assertions().push_back( dtorAssert );
189                //      dst->get_assertions().push_back( copyCtorAssert );
190                // }
191
192                TypeDecl *dst = new TypeDecl( src->get_name(), src->get_storageClass(), 0, src->get_kind() );
193                cloneAll(src->get_assertions(), dst->get_assertions());
194                return dst;
195        }
196
197        void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric, bool forward = true ) {
198                if ( isGeneric ) {
199                        // rewrite member type in terms of the type variables on this operator
200                        field = field->clone();
201                        genericSubs.apply( field );
202
203                        if ( src ) {
204                                genericSubs.apply( src );
205                        }
206                }
207
208                ObjectDecl * returnVal = NULL;
209                if ( ! func->get_functionType()->get_returnVals().empty() ) {
210                        returnVal = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_returnVals().front() );
211                }
212
213                // assign to destination (and return value if generic)
214                if ( ArrayType *array = dynamic_cast< ArrayType * >( field->get_type() ) ) {
215                        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
216                        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
217                        Expression *dstselect = new MemberExpr( field, derefExpr );
218
219                        makeArrayFunction( src, dstselect, array, func->get_name(), back_inserter( func->get_statements()->get_kids() ), forward );
220                        if ( isGeneric && returnVal ) {
221                                UntypedExpr *derefRet = new UntypedExpr( new NameExpr( "*?" ) );
222                                derefRet->get_args().push_back( new VariableExpr( returnVal ) );
223                                Expression *retselect = new MemberExpr( field, derefRet );
224
225                                makeArrayFunction( src, retselect, array, func->get_name(), back_inserter( func->get_statements()->get_kids() ), forward );
226                        }
227                } else {
228                        makeScalarFunction( src, dstParam, field, func->get_name(), back_inserter( func->get_statements()->get_kids() ) );
229                        if ( isGeneric && returnVal ) makeScalarFunction( src, returnVal, field, func->get_name(), back_inserter( func->get_statements()->get_kids() ) );
230                } // if
231        }
232
233        template<typename Iterator>
234        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric, bool forward = true ) {
235                for ( ; member != end; ++member ) {
236                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
237                                // query the type qualifiers of this field and skip assigning it if it is marked const.
238                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
239                                Type * type = field->get_type();
240                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
241                                        type = at->get_base();
242                                }
243
244                                if ( type->get_qualifiers().isConst ) {
245                                        // don't assign const members
246                                        continue;
247                                }
248
249                                if ( field->get_name() == "" ) {
250                                        // don't assign to anonymous members
251                                        // xxx - this is a temporary fix. Anonymous members tie into
252                                        // our inheritance model. I think the correct way to handle this is to
253                                        // cast the structure to the type of the member and let the resolver
254                                        // figure out whether it's valid and have a pass afterwards that fixes
255                                        // the assignment to use pointer arithmetic with the offset of the
256                                        // member, much like how generic type members are handled.
257                                        continue;
258                                }
259
260                                assert( ! func->get_functionType()->get_parameters().empty() );
261                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
262                                ObjectDecl * srcParam = NULL;
263                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
264                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
265                                }
266                                // srcParam may be NULL, in which case we have default ctor/dtor
267                                assert( dstParam );
268
269                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
270                                makeStructMemberOp( dstParam, srcselect, field, func, genericSubs, isGeneric, forward );
271                        } // if
272                } // for
273        } // makeStructFunctionBody
274
275        /// generate the body of a constructor which takes parameters that match fields, e.g.
276        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
277        template<typename Iterator>
278        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, TypeSubstitution & genericSubs, bool isGeneric ) {
279                FunctionType * ftype = func->get_functionType();
280                std::list<DeclarationWithType*> & params = ftype->get_parameters();
281                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
282
283                // skip 'this' parameter
284                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
285                assert( dstParam );
286                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
287                for ( ; member != end; ++member ) {
288                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
289                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
290                                        // don't make a function whose parameter is an unnamed bitfield
291                                        continue;
292                                } else if ( field->get_name() == "" ) {
293                                        // don't assign to anonymous members
294                                        // xxx - this is a temporary fix. Anonymous members tie into
295                                        // our inheritance model. I think the correct way to handle this is to
296                                        // cast the structure to the type of the member and let the resolver
297                                        // figure out whether it's valid and have a pass afterwards that fixes
298                                        // the assignment to use pointer arithmetic with the offset of the
299                                        // member, much like how generic type members are handled.
300                                        continue;
301                                } else if ( parameter != params.end() ) {
302                                        // matching parameter, initialize field with copy ctor
303                                        Expression *srcselect = new VariableExpr(*parameter);
304                                        makeStructMemberOp( dstParam, srcselect, field, func, genericSubs, isGeneric );
305                                        ++parameter;
306                                } else {
307                                        // no matching parameter, initialize field with default ctor
308                                        makeStructMemberOp( dstParam, NULL, field, func, genericSubs, isGeneric );
309                                }
310                        }
311                }
312        }
313
314        void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
315                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
316
317                // Make function polymorphic in same parameters as generic struct, if applicable
318                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
319                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
320                std::list< Expression* > structParams;  // List of matching parameters to put on types
321                TypeSubstitution genericSubs; // Substitutions to make to member types of struct
322                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
323                        isGeneric = true;
324                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
325                        assignType->get_forall().push_back( typeParam );
326                        TypeInstType *newParamType = new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam );
327                        genericSubs.add( (*param)->get_name(), newParamType );
328                        structParams.push_back( new TypeExpr( newParamType ) );
329                }
330
331                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 );
332                assignType->get_parameters().push_back( dstParam );
333
334                // void ?{}(T *); void ^?{}(T *);
335                FunctionType *ctorType = assignType->clone();
336                FunctionType *dtorType = assignType->clone();
337
338                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
339                assignType->get_parameters().push_back( srcParam );
340
341                // void ?{}(T *, T);
342                FunctionType *copyCtorType = assignType->clone();
343
344                // T ?=?(T *, T);
345                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 );
346                assignType->get_returnVals().push_back( returnVal );
347
348                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
349                // because each unit generates copies of the default routines for each aggregate.
350                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
351                FunctionDecl *ctorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, new CompoundStmt( noLabels ), true, false );
352                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, copyCtorType, new CompoundStmt( noLabels ), true, false );
353                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, dtorType, new CompoundStmt( noLabels ), true, false );
354                assignDecl->fixUniqueId();
355                ctorDecl->fixUniqueId();
356                copyCtorDecl->fixUniqueId();
357                dtorDecl->fixUniqueId();
358
359                // create constructors which take each member type as a parameter.
360                // for example, for struct A { int x, y; }; generate
361                // void ?{}(A *, int) and void ?{}(A *, int, int)
362                std::list<Declaration *> memCtors;
363                FunctionType * memCtorType = ctorType->clone();
364                for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
365                        DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
366                        assert( member );
367                        if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
368                                // don't make a function whose parameter is an unnamed bitfield
369                                continue;
370                        } else if ( member->get_name() == "" ) {
371                                // don't assign to anonymous members
372                                // xxx - this is a temporary fix. Anonymous members tie into
373                                // our inheritance model. I think the correct way to handle this is to
374                                // cast the structure to the type of the member and let the resolver
375                                // figure out whether it's valid and have a pass afterwards that fixes
376                                // the assignment to use pointer arithmetic with the offset of the
377                                // member, much like how generic type members are handled.
378                                continue;
379                        }
380                        memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
381                        FunctionDecl * ctor = new FunctionDecl( "?{}", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, memCtorType->clone(), new CompoundStmt( noLabels ), true, false );
382                        ctor->fixUniqueId();
383                        makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, genericSubs, isGeneric );
384                        memCtors.push_back( ctor );
385                }
386                delete memCtorType;
387
388                // generate appropriate calls to member ctor, assignment
389                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), assignDecl, genericSubs, isGeneric );
390                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctorDecl, genericSubs, isGeneric );
391                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), copyCtorDecl, genericSubs, isGeneric );
392                // needs to do everything in reverse, so pass "forward" as false
393                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dtorDecl, genericSubs, isGeneric, false );
394
395                if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
396
397                declsToAdd.push_back( assignDecl );
398                declsToAdd.push_back( ctorDecl );
399                declsToAdd.push_back( copyCtorDecl );
400                declsToAdd.push_back( dtorDecl );
401                declsToAdd.splice( declsToAdd.end(), memCtors );
402        }
403
404        void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
405                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
406
407                // Make function polymorphic in same parameters as generic union, if applicable
408                bool isGeneric = false;  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for struct)
409                std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters();
410                std::list< Expression* > unionParams;  // List of matching parameters to put on types
411                for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) {
412                        isGeneric = true;
413                        TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() );
414                        assignType->get_forall().push_back( typeParam );
415                        unionParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) );
416                }
417
418                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, unionParams ) ), 0 );
419                assignType->get_parameters().push_back( dstParam );
420
421                // default ctor/dtor need only first parameter
422                FunctionType * ctorType = assignType->clone();
423                FunctionType * dtorType = assignType->clone();
424
425                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
426                assignType->get_parameters().push_back( srcParam );
427
428                // copy ctor needs both parameters
429                FunctionType * copyCtorType = assignType->clone();
430
431                // assignment needs both and return value
432                ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 );
433                assignType->get_returnVals().push_back( returnVal );
434
435                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
436                // because each unit generates copies of the default routines for each aggregate.
437                FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
438                FunctionDecl *ctorDecl = new FunctionDecl( "?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, ctorType, new CompoundStmt( noLabels ), true, false );
439                FunctionDecl *copyCtorDecl = new FunctionDecl( "?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, copyCtorType, NULL, true, false );
440                FunctionDecl *dtorDecl = new FunctionDecl( "^?{}",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, dtorType, new CompoundStmt( noLabels ), true, false );
441
442                assignDecl->fixUniqueId();
443                ctorDecl->fixUniqueId();
444                copyCtorDecl->fixUniqueId();
445                dtorDecl->fixUniqueId();
446
447                makeUnionFieldsAssignment( srcParam, dstParam, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
448                if ( isGeneric ) makeUnionFieldsAssignment( srcParam, returnVal, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) );
449
450                if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
451
452                // body of assignment and copy ctor is the same
453                copyCtorDecl->set_statements( assignDecl->get_statements()->clone() );
454
455                declsToAdd.push_back( assignDecl );
456                declsToAdd.push_back( ctorDecl );
457                declsToAdd.push_back( copyCtorDecl );
458                declsToAdd.push_back( dtorDecl );
459        }
460
461        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
462                if ( ! enumDecl->get_members().empty() ) {
463                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
464                        // enumInst->set_baseEnum( enumDecl );
465                        // declsToAdd.push_back(
466                        makeEnumFunctions( enumDecl, enumInst, functionNesting, declsToAdd );
467                }
468        }
469
470        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
471                if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
472                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
473                        structInst.set_baseStruct( structDecl );
474                        makeStructFunctions( structDecl, &structInst, functionNesting, declsToAdd );
475                        structsDone.insert( structDecl->get_name() );
476                } // if
477        }
478
479        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
480                if ( ! unionDecl->get_members().empty() ) {
481                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
482                        unionInst.set_baseUnion( unionDecl );
483                        makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAdd );
484                } // if
485        }
486
487        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
488                CompoundStmt *stmts = 0;
489                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
490                typeInst->set_baseType( typeDecl );
491                ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
492                ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
493                if ( typeDecl->get_base() ) {
494                        // xxx - generate ctor/dtors for typedecls, e.g.
495                        // otype T = int *;
496                        stmts = new CompoundStmt( std::list< Label >() );
497                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
498                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
499                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
500                        stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
501                } // if
502                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
503                type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
504                type->get_parameters().push_back( dst );
505                type->get_parameters().push_back( src );
506                FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, true, false );
507                declsToAdd.push_back( func );
508        }
509
510        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
511                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
512                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
513                } // for
514                declsToAdd.clear();
515        }
516
517        void AutogenerateRoutines::visit( FunctionType *) {
518                // ensure that we don't add assignment ops for types defined as part of the function
519        }
520
521        void AutogenerateRoutines::visit( PointerType *) {
522                // ensure that we don't add assignment ops for types defined as part of the pointer
523        }
524
525        void AutogenerateRoutines::visit( TraitDecl *) {
526                // ensure that we don't add assignment ops for types defined as part of the trait
527        }
528
529        template< typename StmtClass >
530        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
531                std::set< std::string > oldStructs = structsDone;
532                addVisit( stmt, *this );
533                structsDone = oldStructs;
534        }
535
536        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
537                maybeAccept( functionDecl->get_functionType(), *this );
538                acceptAll( functionDecl->get_oldDecls(), *this );
539                functionNesting += 1;
540                maybeAccept( functionDecl->get_statements(), *this );
541                functionNesting -= 1;
542        }
543
544        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
545                visitStatement( compoundStmt );
546        }
547
548        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
549                visitStatement( switchStmt );
550        }
551} // SymTab
Note: See TracBrowser for help on using the repository browser.