source: src/InitTweak/GenInit.cc @ 598dc68

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since 598dc68 was 4ec9513, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Converted validate C, including adding DimensionExpr? to the new ast.

  • Property mode set to 100644
File size: 27.9 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// GenInit.cc --
8//
9// Author           : Rob Schluntz
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Mon Oct 25 13:53:00 2021
13// Update Count     : 186
14//
15#include "GenInit.h"
16
17#include <stddef.h>                    // for NULL
18#include <algorithm>                   // for any_of
19#include <cassert>                     // for assert, strict_dynamic_cast, assertf
20#include <deque>
21#include <iterator>                    // for back_inserter, inserter, back_inse...
22#include <list>                        // for _List_iterator, list
23
24#include "AST/Decl.hpp"
25#include "AST/Init.hpp"
26#include "AST/Pass.hpp"
27#include "AST/Node.hpp"
28#include "AST/Stmt.hpp"
29#include "CompilationState.h"
30#include "CodeGen/OperatorTable.h"
31#include "Common/PassVisitor.h"        // for PassVisitor, WithGuards, WithShort...
32#include "Common/SemanticError.h"      // for SemanticError
33#include "Common/UniqueName.h"         // for UniqueName
34#include "Common/utility.h"            // for ValueGuard, maybeClone
35#include "GenPoly/GenPoly.h"           // for getFunctionType, isPolyType
36#include "GenPoly/ScopedSet.h"         // for ScopedSet, ScopedSet<>::const_iter...
37#include "InitTweak.h"                 // for isConstExpr, InitExpander, checkIn...
38#include "ResolvExpr/Resolver.h"
39#include "SymTab/Autogen.h"            // for genImplicitCall
40#include "SymTab/Mangler.h"            // for Mangler
41#include "SynTree/LinkageSpec.h"       // for isOverridable, C
42#include "SynTree/Declaration.h"       // for ObjectDecl, DeclarationWithType
43#include "SynTree/Expression.h"        // for VariableExpr, UntypedExpr, Address...
44#include "SynTree/Initializer.h"       // for ConstructorInit, SingleInit, Initi...
45#include "SynTree/Label.h"             // for Label
46#include "SynTree/Mutator.h"           // for mutateAll
47#include "SynTree/Statement.h"         // for CompoundStmt, ImplicitCtorDtorStmt
48#include "SynTree/Type.h"              // for Type, ArrayType, Type::Qualifiers
49#include "SynTree/Visitor.h"           // for acceptAll, maybeAccept
50#include "Tuples/Tuples.h"             // for maybeImpure
51#include "Validate/FindSpecialDecls.h" // for SizeType
52
53namespace InitTweak {
54        namespace {
55                const std::list<Label> noLabels;
56                const std::list<Expression *> noDesignators;
57        }
58
59        struct ReturnFixer : public WithStmtsToAdd, public WithGuards {
60                /// consistently allocates a temporary variable for the return value
61                /// of a function so that anything which the resolver decides can be constructed
62                /// into the return type of a function can be returned.
63                static void makeReturnTemp( std::list< Declaration * > &translationUnit );
64
65                void premutate( FunctionDecl *functionDecl );
66                void premutate( ReturnStmt * returnStmt );
67
68          protected:
69                FunctionType * ftype = nullptr;
70                std::string funcName;
71        };
72
73        struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor>  {
74                /// create constructor and destructor statements for object declarations.
75                /// the actual call statements will be added in after the resolver has run
76                /// so that the initializer expression is only removed if a constructor is found
77                /// and the same destructor call is inserted in all of the appropriate locations.
78                static void generateCtorDtor( std::list< Declaration * > &translationUnit );
79
80                void previsit( ObjectDecl * );
81                void previsit( FunctionDecl *functionDecl );
82
83                // should not traverse into any of these declarations to find objects
84                // that need to be constructed or destructed
85                void previsit( StructDecl *aggregateDecl );
86                void previsit( AggregateDecl * ) { visit_children = false; }
87                void previsit( NamedTypeDecl * ) { visit_children = false; }
88                void previsit( FunctionType * ) { visit_children = false; }
89
90                void previsit( CompoundStmt * compoundStmt );
91
92          private:
93                // set of mangled type names for which a constructor or destructor exists in the current scope.
94                // these types require a ConstructorInit node to be generated, anything else is a POD type and thus
95                // should not have a ConstructorInit generated.
96
97                ManagedTypes managedTypes;
98                bool inFunction = false;
99        };
100
101        struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer {
102                /// hoist dimension from array types in object declaration so that it uses a single
103                /// const variable of type size_t, so that side effecting array dimensions are only
104                /// computed once.
105                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
106
107                void premutate( ObjectDecl * objectDecl );
108                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
109                void premutate( FunctionDecl *functionDecl );
110                // should not traverse into any of these declarations to find objects
111                // that need to be constructed or destructed
112                void premutate( AggregateDecl * ) { visit_children = false; }
113                void premutate( NamedTypeDecl * ) { visit_children = false; }
114                void premutate( FunctionType * ) { visit_children = false; }
115
116                // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *)
117                void premutate( EnumDecl * ) {}
118
119                void hoist( Type * type );
120
121                Type::StorageClasses storageClasses;
122                bool inFunction = false;
123        };
124
125        struct HoistArrayDimension_NoResolve final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards {
126                /// hoist dimension from array types in object declaration so that it uses a single
127                /// const variable of type size_t, so that side effecting array dimensions are only
128                /// computed once.
129                static void hoistArrayDimension( std::list< Declaration * > & translationUnit );
130
131                void premutate( ObjectDecl * objectDecl );
132                DeclarationWithType * postmutate( ObjectDecl * objectDecl );
133                void premutate( FunctionDecl *functionDecl );
134                // should not traverse into any of these declarations to find objects
135                // that need to be constructed or destructed
136                void premutate( AggregateDecl * ) { visit_children = false; }
137                void premutate( NamedTypeDecl * ) { visit_children = false; }
138                void premutate( FunctionType * ) { visit_children = false; }
139
140                void hoist( Type * type );
141
142                Type::StorageClasses storageClasses;
143                bool inFunction = false;
144        };
145
146        void genInit( std::list< Declaration * > & translationUnit ) {
147                if (!useNewAST) {
148                        HoistArrayDimension::hoistArrayDimension( translationUnit );
149                }
150                else {
151                        HoistArrayDimension_NoResolve::hoistArrayDimension( translationUnit );
152                }
153                fixReturnStatements( translationUnit );
154
155                if (!useNewAST) {
156                        CtorDtor::generateCtorDtor( translationUnit );
157                }
158        }
159
160        void fixReturnStatements( std::list< Declaration * > & translationUnit ) {
161                PassVisitor<ReturnFixer> fixer;
162                mutateAll( translationUnit, fixer );
163        }
164
165        void ReturnFixer::premutate( ReturnStmt *returnStmt ) {
166                std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals();
167                assert( returnVals.size() == 0 || returnVals.size() == 1 );
168                // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address
169                // is being returned
170                if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) {
171                        // explicitly construct the return value using the return expression and the retVal object
172                        assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() );
173
174                        ObjectDecl * retVal = strict_dynamic_cast< ObjectDecl * >( returnVals.front() );
175                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( returnStmt->expr ) ) {
176                                // return statement has already been mutated - don't need to do it again
177                                if ( varExpr->var == retVal ) return;
178                        }
179                        Statement * stmt = genCtorDtor( "?{}", retVal, returnStmt->expr );
180                        assertf( stmt, "ReturnFixer: genCtorDtor returned nullptr: %s / %s", toString( retVal ).c_str(), toString( returnStmt->expr ).c_str() );
181                        stmtsToAddBefore.push_back( stmt );
182
183                        // return the retVal object
184                        returnStmt->expr = new VariableExpr( returnVals.front() );
185                } // if
186        }
187
188        void ReturnFixer::premutate( FunctionDecl *functionDecl ) {
189                GuardValue( ftype );
190                GuardValue( funcName );
191
192                ftype = functionDecl->type;
193                funcName = functionDecl->name;
194        }
195
196        // precompute array dimension expression, because constructor generation may duplicate it,
197        // which would be incorrect if it is a side-effecting computation.
198        void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
199                PassVisitor<HoistArrayDimension> hoister;
200                mutateAll( translationUnit, hoister );
201        }
202
203        void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) {
204                GuardValue( storageClasses );
205                storageClasses = objectDecl->get_storageClasses();
206        }
207
208        DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) {
209                hoist( objectDecl->get_type() );
210                return objectDecl;
211        }
212
213        void HoistArrayDimension::hoist( Type * type ) {
214                // if in function, generate const size_t var
215                static UniqueName dimensionName( "_array_dim" );
216
217                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
218                if ( ! inFunction ) return;
219                if ( storageClasses.is_static ) return;
220
221                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
222                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
223
224                        // need to resolve array dimensions in order to accurately determine if constexpr
225                        ResolvExpr::findSingleExpression( arrayType->dimension, Validate::SizeType->clone(), indexer );
226                        // array is variable-length when the dimension is not constexpr
227                        arrayType->isVarLen = ! isConstExpr( arrayType->dimension );
228                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
229                        // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve
230                        // still try to detect constant expressions
231                        if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return;
232
233                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
234                        arrayDimension->get_type()->set_const( true );
235
236                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
237                        declsToAddBefore.push_back( arrayDimension );
238
239                        hoist( arrayType->get_base() );
240                        return;
241                }
242        }
243
244        void HoistArrayDimension::premutate( FunctionDecl * ) {
245                GuardValue( inFunction );
246                inFunction = true;
247        }
248
249        // precompute array dimension expression, because constructor generation may duplicate it,
250        // which would be incorrect if it is a side-effecting computation.
251        void HoistArrayDimension_NoResolve::hoistArrayDimension( std::list< Declaration * > & translationUnit ) {
252                PassVisitor<HoistArrayDimension_NoResolve> hoister;
253                mutateAll( translationUnit, hoister );
254        }
255
256        void HoistArrayDimension_NoResolve::premutate( ObjectDecl * objectDecl ) {
257                GuardValue( storageClasses );
258                storageClasses = objectDecl->get_storageClasses();
259        }
260
261        DeclarationWithType * HoistArrayDimension_NoResolve::postmutate( ObjectDecl * objectDecl ) {
262                hoist( objectDecl->get_type() );
263                return objectDecl;
264        }
265
266        void HoistArrayDimension_NoResolve::hoist( Type * type ) {
267                // if in function, generate const size_t var
268                static UniqueName dimensionName( "_array_dim" );
269
270                // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension.
271                if ( ! inFunction ) return;
272                if ( storageClasses.is_static ) return;
273
274                if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
275                        if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist?
276                        // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects.
277                        // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve
278                        // still try to detect constant expressions
279                        if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return;
280
281                        ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) );
282                        arrayDimension->get_type()->set_const( true );
283
284                        arrayType->set_dimension( new VariableExpr( arrayDimension ) );
285                        declsToAddBefore.push_back( arrayDimension );
286
287                        hoist( arrayType->get_base() );
288                        return;
289                }
290        }
291
292        void HoistArrayDimension_NoResolve::premutate( FunctionDecl * ) {
293                GuardValue( inFunction );
294                inFunction = true;
295        }
296
297namespace {
298
299#       warning Remove the _New suffix after the conversion is complete.
300        struct HoistArrayDimension_NoResolve_New final :
301                        public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting,
302                        public ast::WithGuards, public ast::WithConstTranslationUnit,
303                        public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New> {
304                void previsit( const ast::ObjectDecl * decl );
305                const ast::DeclWithType * postvisit( const ast::ObjectDecl * decl );
306                // Do not look for objects inside there declarations (and type).
307                void previsit( const ast::AggregateDecl * ) { visit_children = false; }
308                void previsit( const ast::NamedTypeDecl * ) { visit_children = false; }
309                void previsit( const ast::FunctionType * ) { visit_children = false; }
310
311                const ast::Type * hoist( const ast::Type * type );
312
313                ast::Storage::Classes storageClasses;
314        };
315
316        void HoistArrayDimension_NoResolve_New::previsit(
317                        const ast::ObjectDecl * decl ) {
318                GuardValue( storageClasses ) = decl->storage;
319        }
320
321        const ast::DeclWithType * HoistArrayDimension_NoResolve_New::postvisit(
322                        const ast::ObjectDecl * objectDecl ) {
323                return mutate_field( objectDecl, &ast::ObjectDecl::type,
324                                hoist( objectDecl->type ) );
325        }
326
327        const ast::Type * HoistArrayDimension_NoResolve_New::hoist(
328                        const ast::Type * type ) {
329                static UniqueName dimensionName( "_array_dim" );
330
331                if ( !isInFunction() || storageClasses.is_static ) {
332                        return type;
333                }
334
335                if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) {
336                        if ( nullptr == arrayType->dimension ) {
337                                return type;
338                        }
339
340                        if ( !Tuples::maybeImpure( arrayType->dimension ) ) {
341                                return type;
342                        }
343
344                        ast::ptr<ast::Type> dimType = transUnit().global.sizeType;
345                        assert( dimType );
346                        add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
347
348                        ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
349                                arrayType->dimension->location,
350                                dimensionName.newName(),
351                                dimType,
352                                new ast::SingleInit(
353                                        arrayType->dimension->location,
354                                        arrayType->dimension
355                                )
356                        );
357
358                        ast::ArrayType * mutType = ast::mutate( arrayType );
359                        mutType->dimension = new ast::VariableExpr(
360                                        arrayDimension->location, arrayDimension );
361                        declsToAddBefore.push_back( arrayDimension );
362
363                        mutType->base = hoist( mutType->base );
364                        return mutType;
365                }
366                return type;
367        }
368
369        struct ReturnFixer_New final :
370                        public ast::WithStmtsToAdd<>, ast::WithGuards {
371                void previsit( const ast::FunctionDecl * decl );
372                const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt );
373        private:
374                const ast::FunctionDecl * funcDecl = nullptr;
375        };
376
377        void ReturnFixer_New::previsit( const ast::FunctionDecl * decl ) {
378                GuardValue( funcDecl ) = decl;
379        }
380
381        const ast::ReturnStmt * ReturnFixer_New::previsit(
382                        const ast::ReturnStmt * stmt ) {
383                auto & returns = funcDecl->returns;
384                assert( returns.size() < 2 );
385                // Hands off if the function returns a reference.
386                // Don't allocate a temporary if the address is returned.
387                if ( stmt->expr && 1 == returns.size() ) {
388                        ast::ptr<ast::DeclWithType> retDecl = returns.front();
389                        if ( isConstructable( retDecl->get_type() ) ) {
390                                // Explicitly construct the return value using the return
391                                // expression and the retVal object.
392                                assertf( "" != retDecl->name,
393                                        "Function %s has unnamed return value.\n",
394                                        funcDecl->name.c_str() );
395
396                                auto retVal = retDecl.strict_as<ast::ObjectDecl>();
397                                if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) {
398                                        // Check if the return statement is already set up.
399                                        if ( varExpr->var == retVal ) return stmt;
400                                }
401                                ast::ptr<ast::Stmt> ctorStmt = genCtorDtor(
402                                        retVal->location, "?{}", retVal, stmt->expr );
403                                assertf( ctorStmt,
404                                        "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
405                                        toString( retVal ).c_str(),
406                                        toString( stmt->expr ).c_str() );
407                                stmtsToAddBefore.push_back( ctorStmt );
408
409                                // Return the retVal object.
410                                ast::ReturnStmt * mutStmt = ast::mutate( stmt );
411                                mutStmt->expr = new ast::VariableExpr(
412                                        stmt->location, retDecl );
413                                return mutStmt;
414                        }
415                }
416                return stmt;
417        }
418
419} // namespace
420
421        void genInit( ast::TranslationUnit & transUnit ) {
422                ast::Pass<HoistArrayDimension_NoResolve_New>::run( transUnit );
423                ast::Pass<ReturnFixer_New>::run( transUnit );
424        }
425
426        void fixReturnStatements( ast::TranslationUnit & transUnit ) {
427                ast::Pass<ReturnFixer_New>::run( transUnit );
428        }
429
430        void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) {
431                PassVisitor<CtorDtor> ctordtor;
432                acceptAll( translationUnit, ctordtor );
433        }
434
435        bool ManagedTypes::isManaged( Type * type ) const {
436                // references are never constructed
437                if ( dynamic_cast< ReferenceType * >( type ) ) return false;
438                // need to clear and reset qualifiers when determining if a type is managed
439                ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
440                type->get_qualifiers() = Type::Qualifiers();
441                if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) {
442                        // tuple is also managed if any of its components are managed
443                        if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) {
444                                return true;
445                        }
446                }
447                // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable)
448                return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type );
449        }
450
451        bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const {
452                Type * type = objDecl->get_type();
453                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
454                        // must always construct VLAs with an initializer, since this is an error in C
455                        if ( at->isVarLen && objDecl->init ) return true;
456                        type = at->get_base();
457                }
458                return isManaged( type );
459        }
460
461        // why is this not just on FunctionDecl?
462        void ManagedTypes::handleDWT( DeclarationWithType * dwt ) {
463                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
464                if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) {
465                        std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters();
466                        assert( ! params.empty() );
467                        Type * type = InitTweak::getPointerBase( params.front()->get_type() );
468                        assert( type );
469                        managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) );
470                }
471        }
472
473        void ManagedTypes::handleStruct( StructDecl * aggregateDecl ) {
474                // don't construct members, but need to take note if there is a managed member,
475                // because that means that this type is also managed
476                for ( Declaration * member : aggregateDecl->get_members() ) {
477                        if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
478                                if ( isManaged( field ) ) {
479                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
480                                        // polymorphic constructors make generic types managed types
481                                        StructInstType inst( Type::Qualifiers(), aggregateDecl );
482                                        managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) );
483                                        break;
484                                }
485                        }
486                }
487        }
488
489        void ManagedTypes::beginScope() { managedTypes.beginScope(); }
490        void ManagedTypes::endScope() { managedTypes.endScope(); }
491
492        bool ManagedTypes_new::isManaged( const ast::Type * type ) const {
493                // references are never constructed
494                if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
495                if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
496                        // tuple is also managed if any of its components are managed
497                        for (auto & component : tupleType->types) {
498                                if (isManaged(component)) return true;
499                        }
500                }
501                // need to clear and reset qualifiers when determining if a type is managed
502                // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
503                auto tmp = shallowCopy(type);
504                tmp->qualifiers = {};
505                // delete tmp at return
506                ast::ptr<ast::Type> guard = tmp;
507                // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable)
508                return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
509        }
510
511        bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const {
512                const ast::Type * type = objDecl->type;
513                while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
514                        // must always construct VLAs with an initializer, since this is an error in C
515                        if ( at->isVarLen && objDecl->init ) return true;
516                        type = at->base;
517                }
518                return isManaged( type );
519        }
520
521        void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) {
522                // if this function is a user-defined constructor or destructor, mark down the type as "managed"
523                if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
524                        auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
525                        assert( ! params.empty() );
526                        // Type * type = InitTweak::getPointerBase( params.front() );
527                        // assert( type );
528                        managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
529                }
530        }
531
532        void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) {
533                // don't construct members, but need to take note if there is a managed member,
534                // because that means that this type is also managed
535                for ( auto & member : aggregateDecl->members ) {
536                        if ( auto field = member.as<ast::ObjectDecl>() ) {
537                                if ( isManaged( field ) ) {
538                                        // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
539                                        // polymorphic constructors make generic types managed types
540                                        ast::StructInstType inst( aggregateDecl );
541                                        managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
542                                        break;
543                                }
544                        }
545                }
546        }
547
548        void ManagedTypes_new::beginScope() { managedTypes.beginScope(); }
549        void ManagedTypes_new::endScope() { managedTypes.endScope(); }
550
551        ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) {
552                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
553                assertf( objDecl, "genCtorDtor passed null objDecl" );
554                std::list< Statement * > stmts;
555                InitExpander_old srcParam( maybeClone( arg ) );
556                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl );
557                assert( stmts.size() <= 1 );
558                return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr;
559
560        }
561
562        ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) {
563                assertf(objDecl, "genCtorDtor passed null objDecl");
564                InitExpander_new srcParam(arg);
565                return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
566        }
567
568        ConstructorInit * genCtorInit( ObjectDecl * objDecl ) {
569                // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor
570                // for each constructable object
571                std::list< Statement * > ctor;
572                std::list< Statement * > dtor;
573
574                InitExpander_old srcParam( objDecl->get_init() );
575                InitExpander_old nullParam( (Initializer *)NULL );
576                SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl );
577                SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false );
578
579                // Currently genImplicitCall produces a single Statement - a CompoundStmt
580                // which  wraps everything that needs to happen. As such, it's technically
581                // possible to use a Statement ** in the above calls, but this is inherently
582                // unsafe, so instead we take the slightly less efficient route, but will be
583                // immediately informed if somehow the above assumption is broken. In this case,
584                // we could always wrap the list of statements at this point with a CompoundStmt,
585                // but it seems reasonable at the moment for this to be done by genImplicitCall
586                // itself. It is possible that genImplicitCall produces no statements (e.g. if
587                // an array type does not have a dimension). In this case, it's fine to ignore
588                // the object for the purposes of construction.
589                assert( ctor.size() == dtor.size() && ctor.size() <= 1 );
590                if ( ctor.size() == 1 ) {
591                        // need to remember init expression, in case no ctors exist
592                        // if ctor does exist, want to use ctor expression instead of init
593                        // push this decision to the resolver
594                        assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) );
595                        return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() );
596                }
597                return nullptr;
598        }
599
600        void CtorDtor::previsit( ObjectDecl * objDecl ) {
601                managedTypes.handleDWT( objDecl );
602                // hands off if @=, extern, builtin, etc.
603                // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C
604                if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) {
605                        // constructed objects cannot be designated
606                        if ( isDesignated( objDecl->get_init() ) ) SemanticError( objDecl, "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n" );
607                        // constructed objects should not have initializers nested too deeply
608                        if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " );
609
610                        objDecl->set_init( genCtorInit( objDecl ) );
611                }
612        }
613
614        void CtorDtor::previsit( FunctionDecl *functionDecl ) {
615                visit_children = false;  // do not try and construct parameters or forall parameters
616                GuardValue( inFunction );
617                inFunction = true;
618
619                managedTypes.handleDWT( functionDecl );
620
621                GuardScope( managedTypes );
622                // go through assertions and recursively add seen ctor/dtors
623                for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) {
624                        for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) {
625                                managedTypes.handleDWT( assertion );
626                        }
627                }
628
629                maybeAccept( functionDecl->get_statements(), *visitor );
630        }
631
632        void CtorDtor::previsit( StructDecl *aggregateDecl ) {
633                visit_children = false; // do not try to construct and destruct aggregate members
634
635                managedTypes.handleStruct( aggregateDecl );
636        }
637
638        void CtorDtor::previsit( CompoundStmt * ) {
639                GuardScope( managedTypes );
640        }
641
642ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
643        // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
644        // constructable object
645        InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
646        ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
647       
648        ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( 
649                srcParam, dstParam, loc, "?{}", objDecl );
650        ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( 
651                nullParam, dstParam, loc, "^?{}", objDecl, 
652                SymTab::LoopBackward );
653       
654        // check that either both ctor and dtor are present, or neither
655        assert( (bool)ctor == (bool)dtor );
656
657        if ( ctor ) {
658                // need to remember init expression, in case no ctors exist. If ctor does exist, want to
659                // use ctor expression instead of init.
660                ctor.strict_as< ast::ImplicitCtorDtorStmt >(); 
661                dtor.strict_as< ast::ImplicitCtorDtorStmt >();
662
663                return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
664        }
665
666        return nullptr;
667}
668
669} // namespace InitTweak
670
671// Local Variables: //
672// tab-width: 4 //
673// mode: c++ //
674// compile-command: "make install" //
675// End: //
Note: See TracBrowser for help on using the repository browser.