source: src/SymTab/Autogen.cc @ 4406887

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 4406887 was 490fb92e, checked in by Fangren Yu <f37yu@…>, 4 years ago

move FixInit? to new ast

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