source: src/SymTab/Autogen.cc @ b0dfbc4

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

Merge branch 'master' into references

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