source: src/SymTab/Autogen.cc @ d411426d

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

Refactor autogen for EnumDecl? [fixes #47]

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