source: src/SymTab/Autogen.cc @ 74b007ba

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

Remove unused isDynamicLayout parameter from autogen, add some more debug information

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