source: src/SymTab/Autogen.cc @ f8b69da7

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since f8b69da7 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
RevLine 
[972e6f7]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
[6926a6d]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Apr 27 14:39:06 2018
13// Update Count     : 63
[972e6f7]14//
15
16#include "Autogen.h"
[30f9072]17
18#include <algorithm>               // for count_if
[e3e16bc]19#include <cassert>                 // for strict_dynamic_cast, assert, assertf
[30f9072]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
[be9288a]23#include <utility>                 // for pair
[30f9072]24#include <vector>                  // for vector
25
[9236060]26#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
[e4d6335]27#include "Common/PassVisitor.h"    // for PassVisitor
[30f9072]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
[8b11840]31#include "InitTweak/GenInit.h"     // for fixReturnStatements
32#include "ResolvExpr/Resolver.h"   // for resolveDecl
[30f9072]33#include "SymTab/Mangler.h"        // for Mangler
[9236060]34#include "SynTree/Attribute.h"     // For Attribute
[30f9072]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;
[972e6f7]41
42namespace SymTab {
[5f98ce5]43        Type * SizeType = 0;
[207c7e1d]44
[a117f7c]45        /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
[207c7e1d]46        struct FuncData {
[837ce06]47                typedef FunctionType * (*TypeGen)( Type *, bool );
[a117f7c]48                FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
[207c7e1d]49                std::string fname;
50                TypeGen genType;
51        };
[5f98ce5]52
[189d800]53        struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
[207c7e1d]54                AutogenerateRoutines();
55
[e4d6335]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 );
[972e6f7]62
[e4d6335]63                void previsit( CompoundStmt * compoundStmt );
[972e6f7]64
[1486116]65          private:
[a117f7c]66
[e4d6335]67                GenPoly::ScopedSet< std::string > structsDone;
[1486116]68                unsigned int functionNesting = 0;     // current level of nested functions
[a117f7c]69
[207c7e1d]70                std::vector< FuncData > data;
[1486116]71        };
72
73        /// generates routines for tuple types.
[ac74057]74        struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
[a117f7c]75                void previsit( FunctionDecl * functionDecl );
[1486116]76
[a117f7c]77                void postvisit( TupleType * tupleType );
[1486116]78
[a117f7c]79                void previsit( CompoundStmt * compoundStmt );
[1486116]80
81          private:
82                unsigned int functionNesting = 0;     // current level of nested functions
83                GenPoly::ScopedSet< std::string > seenTuples;
[972e6f7]84        };
85
86        void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
[e4d6335]87                PassVisitor<AutogenerateRoutines> generator;
88                acceptAll( translationUnit, generator );
[1486116]89
90                // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
91                // AutogenTupleRoutines tupleGenerator;
[ac74057]92                // acceptAll( translationUnit, tupleGenerator );
[972e6f7]93        }
94
[a117f7c]95        //=============================================================================================
96        // FuncGenerator definitions
97        //=============================================================================================
98        class FuncGenerator {
99        public:
100                std::list< Declaration * > definitions, forwards;
101
[0a267c1]102                FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
[a117f7c]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;
[0a267c1]110                unsigned int functionNesting;
[a117f7c]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:
[0a267c1]123                StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data,  unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
[a117f7c]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
[0a267c1]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
[18ca28e]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
[a117f7c]184        class TypeFuncGenerator : public FuncGenerator {
185                TypeDecl * typeDecl;
186        public:
[0a267c1]187                TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
[a117f7c]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
[356189a]209        bool isUnnamedBitfield( ObjectDecl * obj ) {
[f30b2610]210                return obj != nullptr && obj->name == "" && obj->bitfieldWidth != nullptr;
[356189a]211        }
212
[186fd86]213        /// inserts a forward declaration for functionDecl into declsToAdd
214        void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
215                FunctionDecl * decl = functionDecl->clone();
[f30b2610]216                delete decl->statements;
217                decl->statements = nullptr;
[186fd86]218                declsToAdd.push_back( decl );
219                decl->fixUniqueId();
[972e6f7]220        }
221
[f30b2610]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
[186fd86]232        /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
[837ce06]233        FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
[186fd86]234                FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
[837ce06]235                if ( maybePolymorphic ) {
236                        // only copy in
237                        const auto & typeParams = getGenericParams( paramType );
238                        cloneAll( typeParams, ftype->forall );
239                }
[49148d5]240                ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
[f30b2610]241                ftype->parameters.push_back( dstParam );
[186fd86]242                return ftype;
243        }
[d0f8b19]244
[186fd86]245        /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
[837ce06]246        FunctionType * genCopyType( Type * paramType, bool maybePolymorphic ) {
247                FunctionType *ftype = genDefaultType( paramType, maybePolymorphic );
[68fe077a]248                ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
[f30b2610]249                ftype->parameters.push_back( srcParam );
[186fd86]250                return ftype;
251        }
[d0f8b19]252
[186fd86]253        /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
[837ce06]254        FunctionType * genAssignType( Type * paramType, bool maybePolymorphic ) {
255                FunctionType *ftype = genCopyType( paramType, maybePolymorphic );
[68fe077a]256                ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
[f30b2610]257                ftype->returnVals.push_back( returnVal );
[186fd86]258                return ftype;
259        }
[972e6f7]260
[186fd86]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
[972e6f7]265                // because each unit generates copies of the default routines for each aggregate.
[68fe077a]266                Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
[186fd86]267                LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
[ba3706f]268                FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt(),
[ddfd945]269                                                                                                std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
[186fd86]270                decl->fixUniqueId();
271                return decl;
272        }
[d0f8b19]273
[a117f7c]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 );
[f232977]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() );
[ba3706f]303                                dcl->statements->push_back( new ReturnStmt( new VariableExpr( dstParam ) ) );
[f232977]304                        }
[a117f7c]305                        resolve( dcl );
306                }
307        }
308
309        void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
310                bool concurrent_type = isConcurrentType();
[e220391]311                for ( const FuncData & d : data ) {
[a117f7c]312                        // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
[4ee1efb]313                        FunctionType * ftype = d.genType( type, true );
[a117f7c]314
315                        // destructor for concurrent type must be mutex
[e220391]316                        if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
[a117f7c]317                                ftype->parameters.front()->get_type()->set_mutex( true );
318                        }
319
[e220391]320                        newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
[a117f7c]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 );
[6926a6d]336                } catch ( SemanticErrorException & ) {
[a117f7c]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
[f30b2610]351                if ( ! CodeGen::isDestructor( dcl->name ) ) {
[a117f7c]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
[f30b2610]360                unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
[a117f7c]361
[0a267c1]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
[a117f7c]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)
[0a267c1]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;
[a117f7c]375                        }
[1f370451]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
[54c9000]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 );
[0a267c1]384                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
385                        makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
386                        resolve( ctor );
[a117f7c]387                }
[0a267c1]388                delete memCtorType;
[a117f7c]389        }
390
391        void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
[39f84a4]392                InitTweak::InitExpander srcParam( src );
393
[49148d5]394                // assign to destination
[f30b2610]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 );
[dac0aa9]397        }
398
[972e6f7]399        template<typename Iterator>
[a117f7c]400        void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
[972e6f7]401                for ( ; member != end; ++member ) {
[dac0aa9]402                        if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
[972e6f7]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.
[dac0aa9]405                                Type * type = field->get_type();
[972e6f7]406                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
407                                        type = at->get_base();
408                                }
409
[6fc5c14]410                                if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
[cad355a]411                                        // don't assign const members, but do construct/destruct
[972e6f7]412                                        continue;
413                                }
414
415                                assert( ! func->get_functionType()->get_parameters().empty() );
416                                ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
[8b11840]417                                ObjectDecl * srcParam = nullptr;
[972e6f7]418                                if ( func->get_functionType()->get_parameters().size() == 2 ) {
419                                        srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
420                                }
[1a5ad8c]421
[972e6f7]422                                // srcParam may be NULL, in which case we have default ctor/dtor
423                                assert( dstParam );
424
[8b11840]425                                Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
[a117f7c]426                                makeMemberOp( dstParam, srcselect, field, func, forward );
[972e6f7]427                        } // if
428                } // for
[a117f7c]429        } // makeFunctionBody
[972e6f7]430
[dac0aa9]431        template<typename Iterator>
[a117f7c]432        void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
433                FunctionType * ftype = func->type;
434                std::list<DeclarationWithType*> & params = ftype->parameters;
[dac0aa9]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 ) ) {
[0b4d93ab]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() ) {
[dac0aa9]447                                        // matching parameter, initialize field with copy ctor
448                                        Expression *srcselect = new VariableExpr(*parameter);
[a117f7c]449                                        makeMemberOp( dstParam, srcselect, field, func );
[dac0aa9]450                                        ++parameter;
451                                } else {
452                                        // no matching parameter, initialize field with default ctor
[a117f7c]453                                        makeMemberOp( dstParam, nullptr, field, func );
[189d800]454                                }
[356189a]455                        }
[dac0aa9]456                }
[972e6f7]457        }
458
[0a267c1]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
[186fd86]467        /// generate a single union assignment expression (using memcpy)
468        template< typename OutputIterator >
[0a267c1]469        void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
[186fd86]470                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
[0a267c1]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() ) );
[ba3706f]474                *out++ = new ExprStmt( copy );
[186fd86]475        }
[972e6f7]476
[186fd86]477        /// generates the body of a union assignment/copy constructor/field constructor
[0a267c1]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" ) );
[186fd86]490                }
491        }
[972e6f7]492
[0a267c1]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() ); } );
[972e6f7]498
[0a267c1]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;
[972e6f7]502
[a465caf]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.
[0a267c1]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
[a465caf]512                                break;
513                        }
[1f370451]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 ) );
[0a267c1]520                        FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
521                        ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
[582ee28]522                        srcParam->fixUniqueId();
[0a267c1]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;
[a465caf]528                }
[0a267c1]529                delete memCtorType;
[972e6f7]530        }
531
[18ca28e]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 ) );
[ba3706f]550                        funcDecl->statements->push_back( new ExprStmt( callExpr ) );
[18ca28e]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
[a117f7c]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() ) );
[ba3706f]575                dcl->statements->kids.push_back( new ExprStmt( expr ) );
[a117f7c]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
[18ca28e]582        void TypeFuncGenerator::genFieldCtors() {};
[a117f7c]583
584        //=============================================================================================
585        // Visitor definitions
586        //=============================================================================================
[207c7e1d]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.
[a117f7c]590                data.emplace_back( "?{}", genDefaultType );
591                data.emplace_back( "?{}", genCopyType );
592                data.emplace_back( "^?{}", genDefaultType );
593                data.emplace_back( "?=?", genAssignType );
[207c7e1d]594        }
595
[8b11840]596        void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
[189d800]597                // must visit children (enum constants) to add them to the indexer
598                if ( enumDecl->has_body() ) {
[18ca28e]599                        EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
600                        enumInst.set_baseEnum( enumDecl );
601                        EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
602                        generateFunctions( gen, declsToAddAfter );
[972e6f7]603                }
604        }
605
[8b11840]606        void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
[e4d6335]607                visit_children = false;
[a117f7c]608                if ( structDecl->has_body() ) {
[8b11840]609                        StructInstType structInst( Type::Qualifiers(), structDecl->name );
[a117f7c]610                        structInst.set_baseStruct( structDecl );
[8b11840]611                        for ( TypeDecl * typeDecl : structDecl->parameters ) {
612                                structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
[186fd86]613                        }
[a117f7c]614                        StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
615                        generateFunctions( gen, declsToAddAfter );
[972e6f7]616                } // if
617        }
618
[8b11840]619        void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
[e4d6335]620                visit_children = false;
[a117f7c]621                if ( unionDecl->has_body()  ) {
[972e6f7]622                        UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
623                        unionInst.set_baseUnion( unionDecl );
[186fd86]624                        for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
625                                unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
626                        }
[0a267c1]627                        UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
628                        generateFunctions( gen, declsToAddAfter );
[972e6f7]629                } // if
630        }
631
[108f3cdb]632        // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
[8b11840]633        void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
[108f3cdb]634                if ( ! typeDecl->base ) return;
635
636                TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
[0a267c1]637                TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
[a117f7c]638                generateFunctions( gen, declsToAddAfter );
[972e6f7]639
640        }
641
[e4d6335]642        void AutogenerateRoutines::previsit( TraitDecl * ) {
[a5a71d0]643                // ensure that we don't add assignment ops for types defined as part of the trait
[e4d6335]644                visit_children = false;
[972e6f7]645        }
646
[f203a7a]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.
[972e6f7]651                functionNesting += 1;
[f203a7a]652                GuardAction( [this]()  { functionNesting -= 1; } );
[972e6f7]653        }
654
[e4d6335]655        void AutogenerateRoutines::previsit( CompoundStmt * ) {
656                GuardScope( structsDone );
[972e6f7]657        }
[1486116]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                }
[ba3706f]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() ) ) ) );
[1486116]672        }
673
[ac74057]674        void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
[1486116]675                std::string mangleName = SymTab::Mangler::mangleType( tupleType );
[ac74057]676                if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
[1486116]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() ) ) {
[f0ecf9b]694                                        TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
[1486116]695                                        TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
[68fe077a]696                                        newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
[ddfd945]697                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]698                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
[ddfd945]699                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]700                                        newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
[ddfd945]701                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[68fe077a]702                                        newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
[ddfd945]703                                                                                                                                                   std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
[1486116]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
[ac74057]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
[1486116]728        }
729
[ac74057]730        void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
731                visit_children = false;
[a139c11]732                maybeAccept( functionDecl->type, *visitor );
[1486116]733                functionNesting += 1;
[a139c11]734                maybeAccept( functionDecl->statements, *visitor );
[1486116]735                functionNesting -= 1;
736        }
737
[ac74057]738        void AutogenTupleRoutines::previsit( CompoundStmt * ) {
739                GuardScope( seenTuples );
[1486116]740        }
[972e6f7]741} // SymTab
[c0aa336]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.