source: src/SymTab/Autogen.cc @ a139c11

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since a139c11 was a139c11, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Fix previsit in AutogenTupleRoutines?

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