source: src/SymTab/Autogen.cc @ bff227f

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 bff227f was bff227f, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Refactor operator predicates into OperatorTable?.cc

  • Property mode set to 100644
File size: 36.1 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 : Andrew Beach
12// Last Modified On : Wed Jun 28 15:30:00 2017
13// Update Count     : 61
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 "CodeGen/OperatorTable.h"
24#include "AddVisit.h"
25#include "MakeLibCfa.h"
26#include "Autogen.h"
27#include "GenPoly/ScopedSet.h"
28#include "Common/ScopedMap.h"
29#include "SymTab/Mangler.h"
30#include "GenPoly/DeclMutator.h"
31
32namespace SymTab {
33        Type * SizeType = 0;
34        typedef ScopedMap< std::string, bool > TypeMap;
35
36        /// Data used to generate functions generically. Specifically, the name of the generated function, a function which generates the routine protoype, and a map which contains data to determine whether a function should be generated.
37        struct FuncData {
38                typedef FunctionType * (*TypeGen)( Type * );
39                FuncData( const std::string & fname, const TypeGen & genType, TypeMap & map ) : fname( fname ), genType( genType ), map( map ) {}
40                std::string fname;
41                TypeGen genType;
42                TypeMap & map;
43        };
44
45        class AutogenerateRoutines final : public Visitor {
46            template< typename Visitor >
47            friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
48            template< typename Visitor >
49            friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
50          public:
51                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
52
53                typedef Visitor Parent;
54                using Parent::visit;
55
56                AutogenerateRoutines();
57
58                virtual void visit( EnumDecl *enumDecl );
59                virtual void visit( StructDecl *structDecl );
60                virtual void visit( UnionDecl *structDecl );
61                virtual void visit( TypeDecl *typeDecl );
62                virtual void visit( TraitDecl *ctxDecl );
63                virtual void visit( FunctionDecl *functionDecl );
64
65                virtual void visit( FunctionType *ftype );
66                virtual void visit( PointerType *ftype );
67
68                virtual void visit( CompoundStmt *compoundStmt );
69                virtual void visit( SwitchStmt *switchStmt );
70
71          private:
72                template< typename StmtClass > void visitStatement( StmtClass *stmt );
73
74                std::list< Declaration * > declsToAdd, declsToAddAfter;
75                std::set< std::string > structsDone;
76                unsigned int functionNesting = 0;     // current level of nested functions
77                /// Note: the following maps could be ScopedSets, but it should be easier to work
78                /// deleted functions in if they are maps, since the value false can be inserted
79                /// at the current scope without affecting outer scopes or requiring copies.
80                TypeMap copyable, assignable, constructable, destructable;
81                std::vector< FuncData > data;
82        };
83
84        /// generates routines for tuple types.
85        /// Doesn't really need to be a mutator, but it's easier to reuse DeclMutator than it is to use AddVisit
86        /// or anything we currently have that supports adding new declarations for visitors
87        class AutogenTupleRoutines : public GenPoly::DeclMutator {
88          public:
89                typedef GenPoly::DeclMutator Parent;
90                using Parent::mutate;
91
92                virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
93
94                virtual Type * mutate( TupleType *tupleType );
95
96                virtual CompoundStmt * mutate( CompoundStmt *compoundStmt );
97
98          private:
99                unsigned int functionNesting = 0;     // current level of nested functions
100                GenPoly::ScopedSet< std::string > seenTuples;
101        };
102
103        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
104                AutogenerateRoutines generator;
105                acceptAndAdd( translationUnit, generator );
106
107                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
108                // AutogenTupleRoutines tupleGenerator;
109                // tupleGenerator.mutateDeclarationList( translationUnit );
110        }
111
112        bool isUnnamedBitfield( ObjectDecl * obj ) {
113                return obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL;
114        }
115
116        /// inserts a forward declaration for functionDecl into declsToAdd
117        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
118                FunctionDecl * decl = functionDecl->clone();
119                delete decl->get_statements();
120                decl->set_statements( NULL );
121                declsToAdd.push_back( decl );
122                decl->fixUniqueId();
123        }
124
125        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
126        FunctionType * genDefaultType( Type * paramType ) {
127                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
128                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
129                ftype->get_parameters().push_back( dstParam );
130
131                return ftype;
132        }
133
134        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
135        FunctionType * genCopyType( Type * paramType ) {
136                FunctionType *ftype = genDefaultType( paramType );
137                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
138                ftype->get_parameters().push_back( srcParam );
139                return ftype;
140        }
141
142        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
143        FunctionType * genAssignType( Type * paramType ) {
144                FunctionType *ftype = genCopyType( paramType );
145                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
146                ftype->get_returnVals().push_back( returnVal );
147                return ftype;
148        }
149
150        /// true if the aggregate's layout is dynamic
151        template< typename AggrDecl >
152        bool hasDynamicLayout( AggrDecl * aggregateDecl ) {
153                for ( TypeDecl * param : aggregateDecl->get_parameters() ) {
154                        if ( param->isComplete() ) return true;
155                }
156                return false;
157        }
158
159        /// generate a function decl from a name and type. Nesting depth determines whether
160        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
161        FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false  ) {
162                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
163                // because each unit generates copies of the default routines for each aggregate.
164//              DeclarationNode::StorageClass sc = functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static;
165                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
166                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
167                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt( noLabels ),
168                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
169                decl->fixUniqueId();
170                return decl;
171        }
172
173        /// inserts base type of first argument into map if pred(funcDecl) is true
174        void insert( FunctionDecl *funcDecl, TypeMap & map, FunctionDecl * (*pred)(Declaration *) ) {
175                // insert type into constructable, etc. map if appropriate
176                if ( pred( funcDecl ) ) {
177                        FunctionType * ftype = funcDecl->get_functionType();
178                        assert( ! ftype->get_parameters().empty() );
179                        Type * t = InitTweak::getPointerBase( ftype->get_parameters().front()->get_type() );
180                        assert( t );
181                        map.insert( Mangler::mangleType( t ), true );
182                }
183        }
184
185        /// using map and t, determines if is constructable, etc.
186        bool lookup( const TypeMap & map, Type * t ) {
187                if ( dynamic_cast< PointerType * >( t ) ) {
188                        // will need more complicated checking if we want this to work with pointer types, since currently
189                        return true;
190                } else if ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
191                        // an array's constructor, etc. is generated on the fly based on the base type's constructor, etc.
192                        return lookup( map, at->get_base() );
193                }
194                TypeMap::const_iterator it = map.find( Mangler::mangleType( t ) );
195                if ( it != map.end() ) return it->second;
196                // something that does not appear in the map is by default not constructable, etc.
197                return false;
198        }
199
200        /// using map and aggr, examines each member to determine if constructor, etc. should be generated
201        template<typename AggrDecl>
202        bool shouldGenerate( const TypeMap & map, AggrDecl * aggr ) {
203                for ( Declaration * dcl : aggr->get_members() ) {
204                        if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( dcl ) ) {
205                                if ( ! lookup( map, dwt->get_type() ) ) return false;
206                        }
207                }
208                return true;
209        }
210
211        /// data structure for abstracting the generation of special functions
212        template< typename OutputIterator >
213        struct FuncGenerator {
214                StructDecl *aggregateDecl;
215                StructInstType *refType;
216                unsigned int functionNesting;
217                const std::list< TypeDecl* > & typeParams;
218                OutputIterator out;
219                FuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) : aggregateDecl( aggregateDecl ), refType( refType ), functionNesting( functionNesting ), typeParams( typeParams ), out( out ) {}
220
221                /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
222                void gen( const FuncData & data, bool concurrent_type ) {
223                        if ( ! shouldGenerate( data.map, aggregateDecl ) ) return;
224                        FunctionType * ftype = data.genType( refType );
225
226                        if(concurrent_type && CodeGen::isDestructor( data.fname )) {
227                                ftype->get_parameters().front()->get_type()->set_mutex( true );
228                        }
229
230                        cloneAll( typeParams, ftype->get_forall() );
231                        *out++ = genFunc( data.fname, ftype, functionNesting );
232                        data.map.insert( Mangler::mangleType( refType ), true );
233                }
234        };
235
236        template< typename OutputIterator >
237        FuncGenerator<OutputIterator> makeFuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) {
238                return FuncGenerator<OutputIterator>( aggregateDecl, refType, functionNesting, typeParams, out );
239        }
240
241        /// generates a single enumeration assignment expression
242        ApplicationExpr * genEnumAssign( FunctionType * ftype, FunctionDecl * assignDecl ) {
243                // enum copy construct and assignment is just C-style assignment.
244                // this looks like a bad recursive call, but code gen will turn it into
245                // a C-style assignment.
246                // This happens before function pointer type conversion, so need to do it manually here
247                // NOTE: ftype is not necessarily the functionType belonging to assignDecl - ftype is the
248                // type of the function that this expression is being generated for (so that the correct
249                // parameters) are using in the variable exprs
250                assert( ftype->get_parameters().size() == 2 );
251                ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
252                ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
253
254                VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
255                Type * assignVarExprType = assignVarExpr->get_result();
256                assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
257                assignVarExpr->set_result( assignVarExprType );
258                ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
259                assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
260                assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
261                return assignExpr;
262        }
263
264        // E ?=?(E volatile*, int),
265        //   ?=?(E _Atomic volatile*, int);
266        void makeEnumFunctions( EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
267
268                // T ?=?(E *, E);
269                FunctionType *assignType = genAssignType( refType );
270
271                // void ?{}(E *); void ^?{}(E *);
272                FunctionType * ctorType = genDefaultType( refType->clone() );
273                FunctionType * dtorType = genDefaultType( refType->clone() );
274
275                // void ?{}(E *, E);
276                FunctionType *copyCtorType = genCopyType( refType->clone() );
277
278                // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
279                // right now these cases work, but that might change.
280
281                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
282                // Really they're something of a cross between instrinsic and autogen, so should
283                // probably make a new linkage type
284                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting, true );
285                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting, true );
286                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting, true );
287                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting, true );
288
289                // body is either return stmt or expr stmt
290                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, genEnumAssign( assignType, assignDecl ) ) );
291                copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, genEnumAssign( copyCtorType, assignDecl ) ) );
292
293                declsToAdd.push_back( ctorDecl );
294                declsToAdd.push_back( copyCtorDecl );
295                declsToAdd.push_back( dtorDecl );
296                declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
297        }
298
299        /// generates a single struct member operation (constructor call, destructor call, assignment call)
300        void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
301                InitTweak::InitExpander srcParam( src );
302
303                // assign to destination
304                Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), safe_dynamic_cast< ReferenceType* >( dstParam->get_type() )->get_base()->clone() ) );
305                genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
306        }
307
308        /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
309        template<typename Iterator>
310        void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
311                for ( ; member != end; ++member ) {
312                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
313                                // query the type qualifiers of this field and skip assigning it if it is marked const.
314                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
315                                Type * type = field->get_type();
316                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
317                                        type = at->get_base();
318                                }
319
320                                if ( type->get_const() && func->get_name() == "?=?" ) {
321                                        // don't assign const members, but do construct/destruct
322                                        continue;
323                                }
324
325                                if ( field->get_name() == "" ) {
326                                        // don't assign to anonymous members
327                                        // xxx - this is a temporary fix. Anonymous members tie into
328                                        // our inheritance model. I think the correct way to handle this is to
329                                        // cast the structure to the type of the member and let the resolver
330                                        // figure out whether it's valid and have a pass afterwards that fixes
331                                        // the assignment to use pointer arithmetic with the offset of the
332                                        // member, much like how generic type members are handled.
333                                        continue;
334                                }
335
336                                assert( ! func->get_functionType()->get_parameters().empty() );
337                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
338                                ObjectDecl * srcParam = NULL;
339                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
340                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
341                                }
342                                // srcParam may be NULL, in which case we have default ctor/dtor
343                                assert( dstParam );
344
345                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
346                                makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout, forward );
347                        } // if
348                } // for
349        } // makeStructFunctionBody
350
351        /// generate the body of a constructor which takes parameters that match fields, e.g.
352        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
353        template<typename Iterator>
354        void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout ) {
355                FunctionType * ftype = func->get_functionType();
356                std::list<DeclarationWithType*> & params = ftype->get_parameters();
357                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
358
359                // skip 'this' parameter
360                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
361                assert( dstParam );
362                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
363                for ( ; member != end; ++member ) {
364                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
365                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
366                                        // don't make a function whose parameter is an unnamed bitfield
367                                        continue;
368                                } else if ( field->get_name() == "" ) {
369                                        // don't assign to anonymous members
370                                        // xxx - this is a temporary fix. Anonymous members tie into
371                                        // our inheritance model. I think the correct way to handle this is to
372                                        // cast the structure to the type of the member and let the resolver
373                                        // figure out whether it's valid and have a pass afterwards that fixes
374                                        // the assignment to use pointer arithmetic with the offset of the
375                                        // member, much like how generic type members are handled.
376                                        continue;
377                                } else if ( parameter != params.end() ) {
378                                        // matching parameter, initialize field with copy ctor
379                                        Expression *srcselect = new VariableExpr(*parameter);
380                                        makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout );
381                                        ++parameter;
382                                } else {
383                                        // no matching parameter, initialize field with default ctor
384                                        makeStructMemberOp( dstParam, NULL, field, func, isDynamicLayout );
385                                }
386                        }
387                }
388        }
389
390        /// generates struct constructors, destructor, and assignment functions
391        void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd, const std::vector< FuncData > & data ) {
392                // Builtins do not use autogeneration.
393                if ( aggregateDecl->get_linkage() == LinkageSpec::Builtin ||
394                         aggregateDecl->get_linkage() == LinkageSpec::BuiltinC ) {
395                        return;
396                }
397
398                // Make function polymorphic in same parameters as generic struct, if applicable
399                const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
400                bool isDynamicLayout = hasDynamicLayout( aggregateDecl );  // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
401
402                // generate each of the functions based on the supplied FuncData objects
403                std::list< FunctionDecl * > newFuncs;
404                auto generator = makeFuncGenerator( aggregateDecl, refType, functionNesting, typeParams, back_inserter( newFuncs ) );
405                for ( const FuncData & d : data ) {
406                        generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
407                }
408
409                // field ctors are only generated if default constructor and copy constructor are both generated
410                unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
411
412                if ( functionNesting == 0 ) {
413                        // forward declare if top-level struct, so that
414                        // type is complete as soon as its body ends
415                        // Note: this is necessary if we want structs which contain
416                        // generic (otype) structs as members.
417                        for ( FunctionDecl * dcl : newFuncs ) {
418                                addForwardDecl( dcl, declsToAdd );
419                        }
420                }
421
422                for ( FunctionDecl * dcl : newFuncs ) {
423                        // generate appropriate calls to member ctor, assignment
424                        // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
425                        if ( ! CodeGen::isDestructor( dcl->get_name() ) ) {
426                                makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl, isDynamicLayout );
427                        } else {
428                                makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, isDynamicLayout, false );
429                        }
430                        if ( CodeGen::isAssignment( dcl->get_name() ) ) {
431                                // assignment needs to return a value
432                                FunctionType * assignType = dcl->get_functionType();
433                                assert( assignType->get_parameters().size() == 2 );
434                                ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( assignType->get_parameters().back() );
435                                dcl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
436                        }
437                        declsToAdd.push_back( dcl );
438                }
439
440                // create constructors which take each member type as a parameter.
441                // for example, for struct A { int x, y; }; generate
442                //   void ?{}(A *, int) and void ?{}(A *, int, int)
443                // Field constructors are only generated if default and copy constructor
444                // are generated, since they need access to both
445                if ( numCtors == 2 ) {
446                        FunctionType * memCtorType = genDefaultType( refType );
447                        cloneAll( typeParams, memCtorType->get_forall() );
448                        for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
449                                DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
450                                assert( member );
451                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
452                                        // don't make a function whose parameter is an unnamed bitfield
453                                        continue;
454                                } else if ( member->get_name() == "" ) {
455                                        // don't assign to anonymous members
456                                        // xxx - this is a temporary fix. Anonymous members tie into
457                                        // our inheritance model. I think the correct way to handle this is to
458                                        // cast the structure to the type of the member and let the resolver
459                                        // figure out whether it's valid/choose the correct unnamed member
460                                        continue;
461                                }
462                                memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
463                                FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
464                                makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, isDynamicLayout );
465                                declsToAdd.push_back( ctor );
466                        }
467                        delete memCtorType;
468                }
469        }
470
471        /// generate a single union assignment expression (using memcpy)
472        template< typename OutputIterator >
473        void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
474                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
475                copy->get_args().push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
476                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
477                copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
478                *out++ = new ExprStmt( noLabels, copy );
479        }
480
481        /// generates the body of a union assignment/copy constructor/field constructor
482        void makeUnionAssignBody( FunctionDecl * funcDecl ) {
483                FunctionType * ftype = funcDecl->get_functionType();
484                assert( ftype->get_parameters().size() == 2 );
485                ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
486                ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
487
488                makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
489                if ( CodeGen::isAssignment( funcDecl->get_name() ) ) {
490                        // also generate return statement in assignment
491                        funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
492                }
493        }
494
495        /// generates union constructors, destructors, and assignment operator
496        void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
497                // Make function polymorphic in same parameters as generic union, if applicable
498                const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
499
500                // default ctor/dtor need only first parameter
501                // void ?{}(T *); void ^?{}(T *);
502                FunctionType *ctorType = genDefaultType( refType );
503                FunctionType *dtorType = genDefaultType( refType );
504
505                // copy ctor needs both parameters
506                // void ?{}(T *, T);
507                FunctionType *copyCtorType = genCopyType( refType );
508
509                // assignment needs both and return value
510                // T ?=?(T *, T);
511                FunctionType *assignType = genAssignType( refType );
512
513                cloneAll( typeParams, ctorType->get_forall() );
514                cloneAll( typeParams, dtorType->get_forall() );
515                cloneAll( typeParams, copyCtorType->get_forall() );
516                cloneAll( typeParams, assignType->get_forall() );
517
518                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
519                // because each unit generates copies of the default routines for each aggregate.
520                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
521                FunctionDecl *ctorDecl = genFunc( "?{}",  ctorType, functionNesting );
522                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
523                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
524
525                makeUnionAssignBody( assignDecl );
526
527                // body of assignment and copy ctor is the same
528                makeUnionAssignBody( copyCtorDecl );
529
530                // create a constructor which takes the first member type as a parameter.
531                // for example, for Union A { int x; double y; }; generate
532                // void ?{}(A *, int)
533                // This is to mimic C's behaviour which initializes the first member of the union.
534                std::list<Declaration *> memCtors;
535                for ( Declaration * member : aggregateDecl->get_members() ) {
536                        if ( DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ) ) {
537                                ObjectDecl * srcParam = new ObjectDecl( "src", Type::StorageClasses(), LinkageSpec::Cforall, 0, field->get_type()->clone(), 0 );
538
539                                FunctionType * memCtorType = ctorType->clone();
540                                memCtorType->get_parameters().push_back( srcParam );
541                                FunctionDecl * ctor = genFunc( "?{}", memCtorType, functionNesting );
542
543                                makeUnionAssignBody( ctor );
544                                memCtors.push_back( ctor );
545                                // only generate a ctor for the first field
546                                break;
547                        }
548                }
549
550                declsToAdd.push_back( ctorDecl );
551                declsToAdd.push_back( copyCtorDecl );
552                declsToAdd.push_back( dtorDecl );
553                declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
554                declsToAdd.splice( declsToAdd.end(), memCtors );
555        }
556
557        AutogenerateRoutines::AutogenerateRoutines() {
558                // the order here determines the order that these functions are generated.
559                // assignment should come last since it uses copy constructor in return.
560                data.push_back( FuncData( "?{}", genDefaultType, constructable ) );
561                data.push_back( FuncData( "?{}", genCopyType, copyable ) );
562                data.push_back( FuncData( "^?{}", genDefaultType, destructable ) );
563                data.push_back( FuncData( "?=?", genAssignType, assignable ) );
564        }
565
566        void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
567                if ( ! enumDecl->get_members().empty() ) {
568                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
569                        // enumInst->set_baseEnum( enumDecl );
570                        makeEnumFunctions( enumInst, functionNesting, declsToAddAfter );
571                }
572        }
573
574        void AutogenerateRoutines::visit( StructDecl *structDecl ) {
575                if ( structDecl->has_body() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
576                        StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
577                        for ( TypeDecl * typeDecl : structDecl->get_parameters() ) {
578                                // need to visit assertions so that they are added to the appropriate maps
579                                acceptAll( typeDecl->get_assertions(), *this );
580                                structInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
581                        }
582                        structInst.set_baseStruct( structDecl );
583                        makeStructFunctions( structDecl, &structInst, functionNesting, declsToAddAfter, data );
584                        structsDone.insert( structDecl->get_name() );
585                } // if
586        }
587
588        void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
589                if ( ! unionDecl->get_members().empty() ) {
590                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
591                        unionInst.set_baseUnion( unionDecl );
592                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
593                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
594                        }
595                        makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAddAfter );
596                } // if
597        }
598
599        void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
600                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
601                typeInst->set_baseType( typeDecl );
602                ObjectDecl *src = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, typeInst->clone(), nullptr );
603                ObjectDecl *dst = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), typeInst->clone() ), nullptr );
604
605                std::list< Statement * > stmts;
606                if ( typeDecl->get_base() ) {
607                        // xxx - generate ctor/dtors for typedecls, e.g.
608                        // otype T = int *;
609                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
610                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
611                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
612                        stmts.push_back( new ReturnStmt( std::list< Label >(), assign ) );
613                } // if
614                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
615                type->get_returnVals().push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, typeInst, 0 ) );
616                type->get_parameters().push_back( dst );
617                type->get_parameters().push_back( src );
618                FunctionDecl *func = genFunc( "?=?", type, functionNesting );
619                func->get_statements()->get_kids() = stmts;
620                declsToAddAfter.push_back( func );
621        }
622
623        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
624                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
625                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
626                } // for
627                declsToAdd.clear();
628        }
629
630        void AutogenerateRoutines::visit( FunctionType *) {
631                // ensure that we don't add assignment ops for types defined as part of the function
632        }
633
634        void AutogenerateRoutines::visit( PointerType *) {
635                // ensure that we don't add assignment ops for types defined as part of the pointer
636        }
637
638        void AutogenerateRoutines::visit( TraitDecl *) {
639                // ensure that we don't add assignment ops for types defined as part of the trait
640        }
641
642        template< typename StmtClass >
643        inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
644                std::set< std::string > oldStructs = structsDone;
645                addVisit( stmt, *this );
646                structsDone = oldStructs;
647        }
648
649        void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
650                // record the existence of this function as appropriate
651                insert( functionDecl, constructable, InitTweak::isDefaultConstructor );
652                insert( functionDecl, assignable, InitTweak::isAssignment );
653                insert( functionDecl, copyable, InitTweak::isCopyConstructor );
654                insert( functionDecl, destructable, InitTweak::isDestructor );
655
656                maybeAccept( functionDecl->get_functionType(), *this );
657                functionNesting += 1;
658                maybeAccept( functionDecl->get_statements(), *this );
659                functionNesting -= 1;
660        }
661
662        void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
663                constructable.beginScope();
664                assignable.beginScope();
665                copyable.beginScope();
666                destructable.beginScope();
667                visitStatement( compoundStmt );
668                constructable.endScope();
669                assignable.endScope();
670                copyable.endScope();
671                destructable.endScope();
672        }
673
674        void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
675                visitStatement( switchStmt );
676        }
677
678        void makeTupleFunctionBody( FunctionDecl * function ) {
679                FunctionType * ftype = function->get_functionType();
680                assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
681
682                UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
683
684                /// xxx - &* is used to make this easier for later passes to handle
685                untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
686                if ( ftype->get_parameters().size() == 2 ) {
687                        untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
688                }
689                function->get_statements()->get_kids().push_back( new ExprStmt( noLabels, untyped ) );
690                function->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
691        }
692
693        Type * AutogenTupleRoutines::mutate( TupleType * tupleType ) {
694                tupleType = safe_dynamic_cast< TupleType * >( Parent::mutate( tupleType ) );
695                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
696                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return tupleType;
697                seenTuples.insert( mangleName );
698
699                // T ?=?(T *, T);
700                FunctionType *assignType = genAssignType( tupleType );
701
702                // void ?{}(T *); void ^?{}(T *);
703                FunctionType *ctorType = genDefaultType( tupleType );
704                FunctionType *dtorType = genDefaultType( tupleType );
705
706                // void ?{}(T *, T);
707                FunctionType *copyCtorType = genCopyType( tupleType );
708
709                std::set< TypeDecl* > done;
710                std::list< TypeDecl * > typeParams;
711                for ( Type * t : *tupleType ) {
712                        if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
713                                if ( ! done.count( ty->get_baseType() ) ) {
714                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Any );
715                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
716                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
717                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
718                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
719                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
720                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
721                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
722                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
723                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
724                                        typeParams.push_back( newDecl );
725                                        done.insert( ty->get_baseType() );
726                                }
727                        }
728                }
729                cloneAll( typeParams, ctorType->get_forall() );
730                cloneAll( typeParams, dtorType->get_forall() );
731                cloneAll( typeParams, copyCtorType->get_forall() );
732                cloneAll( typeParams, assignType->get_forall() );
733
734                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
735                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
736                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
737                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
738
739                makeTupleFunctionBody( assignDecl );
740                makeTupleFunctionBody( ctorDecl );
741                makeTupleFunctionBody( copyCtorDecl );
742                makeTupleFunctionBody( dtorDecl );
743
744                addDeclaration( ctorDecl );
745                addDeclaration( copyCtorDecl );
746                addDeclaration( dtorDecl );
747                addDeclaration( assignDecl ); // assignment should come last since it uses copy constructor in return
748
749                return tupleType;
750        }
751
752        DeclarationWithType * AutogenTupleRoutines::mutate( FunctionDecl *functionDecl ) {
753                functionDecl->set_functionType( maybeMutate( functionDecl->get_functionType(), *this ) );
754                functionNesting += 1;
755                functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) );
756                functionNesting -= 1;
757                return functionDecl;
758        }
759
760        CompoundStmt * AutogenTupleRoutines::mutate( CompoundStmt *compoundStmt ) {
761                seenTuples.beginScope();
762                compoundStmt = safe_dynamic_cast< CompoundStmt * >( Parent::mutate( compoundStmt ) );
763                seenTuples.endScope();
764                return compoundStmt;
765        }
766} // SymTab
767
768// Local Variables: //
769// tab-width: 4 //
770// mode: c++ //
771// compile-command: "make install" //
772// End: //
Note: See TracBrowser for help on using the repository browser.