source: src/SymTab/Autogen.cc @ b7c89aa

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since b7c89aa was 90152a4, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Merge branch 'master' into cleanup-dtors

  • Property mode set to 100644
File size: 33.6 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Thu Mar 03 15:45:56 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Apr 27 14:39:06 2018
13// Update Count     : 63
14//
15
16#include "Autogen.h"
17
18#include <algorithm>               // for count_if
19#include <cassert>                 // for strict_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 "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
27#include "Common/PassVisitor.h"    // for PassVisitor
28#include "Common/ScopedMap.h"      // for ScopedMap<>::const_iterator, Scope...
29#include "Common/utility.h"        // for cloneAll, operator+
30#include "GenPoly/ScopedSet.h"     // for ScopedSet, ScopedSet<>::iterator
31#include "InitTweak/GenInit.h"     // for fixReturnStatements
32#include "ResolvExpr/Resolver.h"   // for resolveDecl
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
45        /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
46        struct FuncData {
47                typedef FunctionType * (*TypeGen)( Type *, bool );
48                FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
49                std::string fname;
50                TypeGen genType;
51        };
52
53        struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
54                AutogenerateRoutines();
55
56                void previsit( EnumDecl * enumDecl );
57                void previsit( StructDecl * structDecl );
58                void previsit( UnionDecl * structDecl );
59                void previsit( TypeDecl * typeDecl );
60                void previsit( TraitDecl * traitDecl );
61                void previsit( FunctionDecl * functionDecl );
62
63                void previsit( CompoundStmt * compoundStmt );
64
65          private:
66
67                GenPoly::ScopedSet< std::string > structsDone;
68                unsigned int functionNesting = 0;     // current level of nested functions
69
70                std::vector< FuncData > data;
71        };
72
73        /// generates routines for tuple types.
74        struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
75                void previsit( FunctionDecl * functionDecl );
76
77                void postvisit( TupleType * tupleType );
78
79                void previsit( CompoundStmt * compoundStmt );
80
81          private:
82                unsigned int functionNesting = 0;     // current level of nested functions
83                GenPoly::ScopedSet< std::string > seenTuples;
84        };
85
86        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
87                PassVisitor<AutogenerateRoutines> generator;
88                acceptAll( translationUnit, generator );
89
90                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
91                // AutogenTupleRoutines tupleGenerator;
92                // acceptAll( translationUnit, tupleGenerator );
93        }
94
95        //=============================================================================================
96        // FuncGenerator definitions
97        //=============================================================================================
98        class FuncGenerator {
99        public:
100                std::list< Declaration * > definitions, forwards;
101
102                FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
103
104                virtual bool shouldAutogen() const = 0;
105                void genStandardFuncs();
106                virtual void genFieldCtors() = 0;
107        protected:
108                Type * type;
109                const std::vector< FuncData > & data;
110                unsigned int functionNesting;
111                SymTab::Indexer & indexer;
112
113                virtual void genFuncBody( FunctionDecl * dcl ) = 0;
114                virtual bool isConcurrentType() const = 0;
115
116                void resolve( FunctionDecl * dcl );
117                void generatePrototypes( std::list< FunctionDecl * > & newFuncs );
118        };
119
120        class StructFuncGenerator : public FuncGenerator {
121                StructDecl * aggregateDecl;
122        public:
123                StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
124
125                virtual bool shouldAutogen() const override;
126                virtual bool isConcurrentType() const override;
127
128                virtual void genFuncBody( FunctionDecl * dcl ) override;
129                virtual void genFieldCtors() override;
130
131        private:
132                /// generates a single struct member operation (constructor call, destructor call, assignment call)
133                void makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true );
134
135                /// 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
136                template<typename Iterator>
137                void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
138
139                /// generate the body of a constructor which takes parameters that match fields, e.g.
140                /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
141                template<typename Iterator>
142                void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
143        };
144
145        class UnionFuncGenerator : public FuncGenerator {
146                UnionDecl * aggregateDecl;
147        public:
148                UnionFuncGenerator( UnionDecl * aggregateDecl, UnionInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
149
150                virtual bool shouldAutogen() const override;
151                virtual bool isConcurrentType() const override;
152
153                virtual void genFuncBody( FunctionDecl * dcl ) override;
154                virtual void genFieldCtors() override;
155
156        private:
157                /// generates a single struct member operation (constructor call, destructor call, assignment call)
158                template<typename OutputIterator>
159                void makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out );
160
161                /// 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
162                template<typename Iterator>
163                void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
164
165                /// generate the body of a constructor which takes parameters that match fields, e.g.
166                /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
167                template<typename Iterator>
168                void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
169        };
170
171        class EnumFuncGenerator : public FuncGenerator {
172        public:
173                EnumFuncGenerator( EnumInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ) {}
174
175                virtual bool shouldAutogen() const override;
176                virtual bool isConcurrentType() const override;
177
178                virtual void genFuncBody( FunctionDecl * dcl ) override;
179                virtual void genFieldCtors() override;
180
181        private:
182        };
183
184        class TypeFuncGenerator : public FuncGenerator {
185                TypeDecl * typeDecl;
186        public:
187                TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
188
189                virtual bool shouldAutogen() const override;
190                virtual void genFuncBody( FunctionDecl * dcl ) override;
191                virtual bool isConcurrentType() const override;
192                virtual void genFieldCtors() override;
193        };
194
195        //=============================================================================================
196        // helper functions
197        //=============================================================================================
198        void generateFunctions( FuncGenerator & gen, std::list< Declaration * > & declsToAdd ) {
199                if ( ! gen.shouldAutogen() ) return;
200
201                // generate each of the functions based on the supplied FuncData objects
202                gen.genStandardFuncs();
203                gen.genFieldCtors();
204
205                declsToAdd.splice( declsToAdd.end(), gen.forwards );
206                declsToAdd.splice( declsToAdd.end(), gen.definitions );
207        }
208
209        bool isUnnamedBitfield( ObjectDecl * obj ) {
210                return obj != nullptr && obj->name == "" && obj->bitfieldWidth != nullptr;
211        }
212
213        /// inserts a forward declaration for functionDecl into declsToAdd
214        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
215                FunctionDecl * decl = functionDecl->clone();
216                delete decl->statements;
217                decl->statements = nullptr;
218                declsToAdd.push_back( decl );
219                decl->fixUniqueId();
220        }
221
222        const std::list< TypeDecl * > getGenericParams( Type * t ) {
223                std::list< TypeDecl * > * ret = nullptr;
224                if ( StructInstType * inst = dynamic_cast< StructInstType * > ( t ) ) {
225                        ret = inst->get_baseParameters();
226                } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
227                        ret = inst->get_baseParameters();
228                }
229                return ret ? *ret : std::list< TypeDecl * >();
230        }
231
232        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
233        FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
234                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
235                if ( maybePolymorphic ) {
236                        // only copy in
237                        const auto & typeParams = getGenericParams( paramType );
238                        cloneAll( typeParams, ftype->forall );
239                }
240                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
241                ftype->parameters.push_back( dstParam );
242                return ftype;
243        }
244
245        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
246        FunctionType * genCopyType( Type * paramType, bool maybePolymorphic ) {
247                FunctionType *ftype = genDefaultType( paramType, maybePolymorphic );
248                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
249                ftype->parameters.push_back( srcParam );
250                return ftype;
251        }
252
253        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
254        FunctionType * genAssignType( Type * paramType, bool maybePolymorphic ) {
255                FunctionType *ftype = genCopyType( paramType, maybePolymorphic );
256                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
257                ftype->returnVals.push_back( returnVal );
258                return ftype;
259        }
260
261        /// generate a function decl from a name and type. Nesting depth determines whether
262        /// the declaration is static or not; optional paramter determines if declaration is intrinsic
263        FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false  ) {
264                // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
265                // because each unit generates copies of the default routines for each aggregate.
266                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
267                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
268                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt(),
269                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
270                decl->fixUniqueId();
271                return decl;
272        }
273
274        Type * declToType( Declaration * decl ) {
275                if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
276                        return dwt->get_type();
277                }
278                return nullptr;
279        }
280
281        Type * declToTypeDeclBase( Declaration * decl ) {
282                if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
283                        return td->base;
284                }
285                return nullptr;
286        }
287
288        //=============================================================================================
289        // FuncGenerator member definitions
290        //=============================================================================================
291        void FuncGenerator::genStandardFuncs() {
292                std::list< FunctionDecl * > newFuncs;
293                generatePrototypes( newFuncs );
294
295                for ( FunctionDecl * dcl : newFuncs ) {
296                        genFuncBody( dcl );
297                        if ( CodeGen::isAssignment( dcl->name ) ) {
298                                // assignment needs to return a value
299                                FunctionType * assignType = dcl->type;
300                                assert( assignType->parameters.size() == 2 );
301                                assert( assignType->returnVals.size() == 1 );
302                                ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.front() );
303                                dcl->statements->push_back( new ReturnStmt( new VariableExpr( dstParam ) ) );
304                        }
305                        resolve( dcl );
306                }
307        }
308
309        void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
310                bool concurrent_type = isConcurrentType();
311                for ( const FuncData & d : data ) {
312                        // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
313                        FunctionType * ftype = d.genType( type, true );
314
315                        // destructor for concurrent type must be mutex
316                        if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
317                                ftype->parameters.front()->get_type()->set_mutex( true );
318                        }
319
320                        newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
321                }
322        }
323
324        void FuncGenerator::resolve( FunctionDecl * dcl ) {
325                try {
326                        ResolvExpr::resolveDecl( dcl, indexer );
327                        if ( functionNesting == 0 ) {
328                                // forward declare if top-level struct, so that
329                                // type is complete as soon as its body ends
330                                // Note: this is necessary if we want structs which contain
331                                // generic (otype) structs as members.
332                                addForwardDecl( dcl, forwards );
333                        }
334                        definitions.push_back( dcl );
335                        indexer.addId( dcl );
336                } catch ( SemanticErrorException & ) {
337                        // okay if decl does not resolve - that means the function should not be generated
338                        delete dcl;
339                }
340        }
341
342        bool StructFuncGenerator::shouldAutogen() const {
343                // Builtins do not use autogeneration.
344                return ! aggregateDecl->linkage.is_builtin;
345        }
346        bool StructFuncGenerator::isConcurrentType() const { return aggregateDecl->is_thread() || aggregateDecl->is_monitor(); }
347
348        void StructFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
349                // generate appropriate calls to member ctor, assignment
350                // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
351                if ( ! CodeGen::isDestructor( dcl->name ) ) {
352                        makeFunctionBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), dcl );
353                } else {
354                        makeFunctionBody( aggregateDecl->members.rbegin(), aggregateDecl->members.rend(), dcl, false );
355                }
356        }
357
358        void StructFuncGenerator::genFieldCtors() {
359                // field ctors are only generated if default constructor and copy constructor are both generated
360                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
361
362                // Field constructors are only generated if default and copy constructor
363                // are generated, since they need access to both
364                if ( numCtors != 2 ) return;
365
366                // create constructors which take each member type as a parameter.
367                // for example, for struct A { int x, y; }; generate
368                //   void ?{}(A *, int) and void ?{}(A *, int, int)
369                FunctionType * memCtorType = genDefaultType( type );
370                for ( Declaration * member : aggregateDecl->members ) {
371                        DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
372                        if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
373                                // don't make a function whose parameter is an unnamed bitfield
374                                continue;
375                        }
376                        // do not carry over field's attributes to parameter type
377                        Type * paramType = field->get_type()->clone();
378                        deleteAll( paramType->attributes );
379                        paramType->attributes.clear();
380                        // add a parameter corresponding to this field
381                        ObjectDecl * param = new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr );
382                        cloneAll_if( field->attributes, param->attributes, [](Attribute * attr) { return attr->isValidOnFuncParam(); } );
383                        memCtorType->parameters.push_back( param );
384                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
385                        makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
386                        resolve( ctor );
387                }
388                delete memCtorType;
389        }
390
391        void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
392                InitTweak::InitExpander srcParam( src );
393
394                // assign to destination
395                Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->base->clone() ) );
396                genImplicitCall( srcParam, dstselect, func->name, back_inserter( func->statements->kids ), field, forward );
397        }
398
399        template<typename Iterator>
400        void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
401                for ( ; member != end; ++member ) {
402                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
403                                // query the type qualifiers of this field and skip assigning it if it is marked const.
404                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
405                                Type * type = field->get_type();
406                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
407                                        type = at->get_base();
408                                }
409
410                                if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
411                                        // don't assign const members, but do construct/destruct
412                                        continue;
413                                }
414
415                                assert( ! func->get_functionType()->get_parameters().empty() );
416                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
417                                ObjectDecl * srcParam = nullptr;
418                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
419                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
420                                }
421
422                                // srcParam may be NULL, in which case we have default ctor/dtor
423                                assert( dstParam );
424
425                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
426                                makeMemberOp( dstParam, srcselect, field, func, forward );
427                        } // if
428                } // for
429        } // makeFunctionBody
430
431        template<typename Iterator>
432        void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
433                FunctionType * ftype = func->type;
434                std::list<DeclarationWithType*> & params = ftype->parameters;
435                assert( params.size() >= 2 );  // should not call this function for default ctor, etc.
436
437                // skip 'this' parameter
438                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
439                assert( dstParam );
440                std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
441                for ( ; member != end; ++member ) {
442                        if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
443                                if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
444                                        // don't make a function whose parameter is an unnamed bitfield
445                                        continue;
446                                } else if ( parameter != params.end() ) {
447                                        // matching parameter, initialize field with copy ctor
448                                        Expression *srcselect = new VariableExpr(*parameter);
449                                        makeMemberOp( dstParam, srcselect, field, func );
450                                        ++parameter;
451                                } else {
452                                        // no matching parameter, initialize field with default ctor
453                                        makeMemberOp( dstParam, nullptr, field, func );
454                                }
455                        }
456                }
457        }
458
459        bool UnionFuncGenerator::shouldAutogen() const {
460                // Builtins do not use autogeneration.
461                return ! aggregateDecl->linkage.is_builtin;
462        }
463
464        // xxx - is this right?
465        bool UnionFuncGenerator::isConcurrentType() const { return false; };
466
467        /// generate a single union assignment expression (using memcpy)
468        template< typename OutputIterator >
469        void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
470                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
471                copy->args.push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
472                copy->args.push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
473                copy->args.push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
474                *out++ = new ExprStmt( copy );
475        }
476
477        /// generates the body of a union assignment/copy constructor/field constructor
478        void UnionFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
479                FunctionType * ftype = funcDecl->type;
480                if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
481                        assert( ftype->parameters.size() == 2 );
482                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
483                        ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
484                        makeMemberOp( srcParam, dstParam, back_inserter( funcDecl->statements->kids ) );
485                } else {
486                        // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
487                        assert( ftype->parameters.size() == 1 );
488                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
489                        dstParam->attributes.push_back( new Attribute( "unused" ) );
490                }
491        }
492
493        /// generate the body of a constructor which takes parameters that match fields, e.g.
494        /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
495        void UnionFuncGenerator::genFieldCtors() {
496                // field ctors are only generated if default constructor and copy constructor are both generated
497                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
498
499                // Field constructors are only generated if default and copy constructor
500                // are generated, since they need access to both
501                if ( numCtors != 2 ) return;
502
503                // create a constructor which takes the first member type as a parameter.
504                // for example, for Union A { int x; double y; }; generate
505                // void ?{}(A *, int)
506                // This is to mimic C's behaviour which initializes the first member of the union.
507                FunctionType * memCtorType = genDefaultType( type );
508                for ( Declaration * member : aggregateDecl->members ) {
509                        DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
510                        if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
511                                // don't make a function whose parameter is an unnamed bitfield
512                                break;
513                        }
514                        // do not carry over field's attributes to parameter type
515                        Type * paramType = field->get_type()->clone();
516                        deleteAll( paramType->attributes );
517                        paramType->attributes.clear();
518                        // add a parameter corresponding to this field
519                        memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr ) );
520                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
521                        ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
522                        srcParam->fixUniqueId();
523                        ObjectDecl * dstParam = InitTweak::getParamThis( ctor->type );
524                        makeMemberOp( srcParam, dstParam, back_inserter( ctor->statements->kids ) );
525                        resolve( ctor );
526                        // only generate one field ctor for unions
527                        break;
528                }
529                delete memCtorType;
530        }
531
532        void EnumFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
533                // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
534                // Really they're something of a cross between instrinsic and autogen, so should
535                // probably make a new linkage type
536                funcDecl->linkage = LinkageSpec::Intrinsic;
537                FunctionType * ftype = funcDecl->type;
538                if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
539                        assert( ftype->parameters.size() == 2 );
540                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
541                        ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
542
543                        // enum copy construct and assignment is just C-style assignment.
544                        // this looks like a bad recursive call, but code gen will turn it into
545                        // a C-style assignment.
546                        // This happens before function pointer type conversion, so need to do it manually here
547                        ApplicationExpr * callExpr = new ApplicationExpr( VariableExpr::functionPointer( funcDecl ) );
548                        callExpr->get_args().push_back( new VariableExpr( dstParam ) );
549                        callExpr->get_args().push_back( new VariableExpr( srcParam ) );
550                        funcDecl->statements->push_back( new ExprStmt( callExpr ) );
551                } else {
552                        // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
553                        assert( ftype->parameters.size() == 1 );
554                        ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
555                        dstParam->attributes.push_back( new Attribute( "unused" ) );
556                }
557        }
558
559        bool EnumFuncGenerator::shouldAutogen() const { return true; }
560        bool EnumFuncGenerator::isConcurrentType() const { return false; }
561        // enums do not have field constructors
562        void EnumFuncGenerator::genFieldCtors() {}
563
564        bool TypeFuncGenerator::shouldAutogen() const { return true; };
565
566        void TypeFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
567                FunctionType * ftype = dcl->type;
568                assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
569                DeclarationWithType * dst = ftype->parameters.front();
570                DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
571                // generate appropriate calls to member ctor, assignment
572                UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
573                expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
574                if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
575                dcl->statements->kids.push_back( new ExprStmt( expr ) );
576        };
577
578        // xxx - should reach in and determine if base type is concurrent?
579        bool TypeFuncGenerator::isConcurrentType() const { return false; };
580
581        // opaque types do not have field constructors
582        void TypeFuncGenerator::genFieldCtors() {};
583
584        //=============================================================================================
585        // Visitor definitions
586        //=============================================================================================
587        AutogenerateRoutines::AutogenerateRoutines() {
588                // the order here determines the order that these functions are generated.
589                // assignment should come last since it uses copy constructor in return.
590                data.emplace_back( "?{}", genDefaultType );
591                data.emplace_back( "?{}", genCopyType );
592                data.emplace_back( "^?{}", genDefaultType );
593                data.emplace_back( "?=?", genAssignType );
594        }
595
596        void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
597                // must visit children (enum constants) to add them to the indexer
598                if ( enumDecl->has_body() ) {
599                        EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
600                        enumInst.set_baseEnum( enumDecl );
601                        EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
602                        generateFunctions( gen, declsToAddAfter );
603                }
604        }
605
606        void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
607                visit_children = false;
608                if ( structDecl->has_body() ) {
609                        StructInstType structInst( Type::Qualifiers(), structDecl->name );
610                        structInst.set_baseStruct( structDecl );
611                        for ( TypeDecl * typeDecl : structDecl->parameters ) {
612                                structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
613                        }
614                        StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
615                        generateFunctions( gen, declsToAddAfter );
616                } // if
617        }
618
619        void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
620                visit_children = false;
621                if ( unionDecl->has_body()  ) {
622                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
623                        unionInst.set_baseUnion( unionDecl );
624                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
625                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
626                        }
627                        UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
628                        generateFunctions( gen, declsToAddAfter );
629                } // if
630        }
631
632        // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
633        void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
634                if ( ! typeDecl->base ) return;
635
636                TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
637                TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
638                generateFunctions( gen, declsToAddAfter );
639
640        }
641
642        void AutogenerateRoutines::previsit( TraitDecl * ) {
643                // ensure that we don't add assignment ops for types defined as part of the trait
644                visit_children = false;
645        }
646
647        void AutogenerateRoutines::previsit( FunctionDecl * ) {
648                // Track whether we're currently in a function.
649                // Can ignore function type idiosyncrasies, because function type can never
650                // declare a new type.
651                functionNesting += 1;
652                GuardAction( [this]()  { functionNesting -= 1; } );
653        }
654
655        void AutogenerateRoutines::previsit( CompoundStmt * ) {
656                GuardScope( structsDone );
657        }
658
659        void makeTupleFunctionBody( FunctionDecl * function ) {
660                FunctionType * ftype = function->get_functionType();
661                assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
662
663                UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
664
665                /// xxx - &* is used to make this easier for later passes to handle
666                untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
667                if ( ftype->get_parameters().size() == 2 ) {
668                        untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
669                }
670                function->get_statements()->get_kids().push_back( new ExprStmt( untyped ) );
671                function->get_statements()->get_kids().push_back( new ReturnStmt( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
672        }
673
674        void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
675                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
676                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
677                seenTuples.insert( mangleName );
678
679                // T ?=?(T *, T);
680                FunctionType *assignType = genAssignType( tupleType );
681
682                // void ?{}(T *); void ^?{}(T *);
683                FunctionType *ctorType = genDefaultType( tupleType );
684                FunctionType *dtorType = genDefaultType( tupleType );
685
686                // void ?{}(T *, T);
687                FunctionType *copyCtorType = genCopyType( tupleType );
688
689                std::set< TypeDecl* > done;
690                std::list< TypeDecl * > typeParams;
691                for ( Type * t : *tupleType ) {
692                        if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
693                                if ( ! done.count( ty->get_baseType() ) ) {
694                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
695                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
696                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
697                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
698                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
699                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
700                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
701                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
702                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
703                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
704                                        typeParams.push_back( newDecl );
705                                        done.insert( ty->get_baseType() );
706                                }
707                        }
708                }
709                cloneAll( typeParams, ctorType->get_forall() );
710                cloneAll( typeParams, dtorType->get_forall() );
711                cloneAll( typeParams, copyCtorType->get_forall() );
712                cloneAll( typeParams, assignType->get_forall() );
713
714                FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
715                FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
716                FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
717                FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
718
719                makeTupleFunctionBody( assignDecl );
720                makeTupleFunctionBody( ctorDecl );
721                makeTupleFunctionBody( copyCtorDecl );
722                makeTupleFunctionBody( dtorDecl );
723
724                declsToAddBefore.push_back( ctorDecl );
725                declsToAddBefore.push_back( copyCtorDecl );
726                declsToAddBefore.push_back( dtorDecl );
727                declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
728        }
729
730        void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
731                visit_children = false;
732                maybeAccept( functionDecl->type, *visitor );
733                functionNesting += 1;
734                maybeAccept( functionDecl->statements, *visitor );
735                functionNesting -= 1;
736        }
737
738        void AutogenTupleRoutines::previsit( CompoundStmt * ) {
739                GuardScope( seenTuples );
740        }
741} // SymTab
742
743// Local Variables: //
744// tab-width: 4 //
745// mode: c++ //
746// compile-command: "make install" //
747// End: //
Note: See TracBrowser for help on using the repository browser.