source: src/SymTab/Autogen.cc @ 136ccd7

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

Merge branch 'master' into cleanup-dtors

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