source: src/SymTab/Autogen.cc @ 39f4100

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 39f4100 was be9288a, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed errors made by the clean-up tool

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