source: src/InitTweak/FixInit.cc @ a28bc02

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 a28bc02 was a28bc02, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

assignment argument and return value are now always copy constructed

  • Property mode set to 100644
File size: 52.0 KB
RevLine 
[71f4e4f]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// FixInit.h --
8//
9// Author           : Rob Schluntz
10// Created On       : Wed Jan 13 16:29:30 2016
[adcc065]11// Last Modified By : Peter A. Buhr
[615a096]12// Last Modified On : Fri Mar 17 09:13:47 2017
13// Update Count     : 71
[71f4e4f]14//
15
16#include <stack>
17#include <list>
[c2931ea]18#include <iterator>
19#include <algorithm>
[dc86541]20#include <unordered_map>
21#include <unordered_set>
[7b3f66b]22#include "InitTweak.h"
[092528b]23#include "GenInit.h"
[6cf27a07]24#include "FixInit.h"
25#include "FixGlobalInit.h"
[db4ecc5]26#include "ResolvExpr/Resolver.h"
[845cedc]27#include "ResolvExpr/typeops.h"
[71f4e4f]28#include "SynTree/Declaration.h"
29#include "SynTree/Type.h"
30#include "SynTree/Expression.h"
[f9cebb5]31#include "SynTree/Attribute.h"
[71f4e4f]32#include "SynTree/Statement.h"
33#include "SynTree/Initializer.h"
34#include "SynTree/Mutator.h"
[db4ecc5]35#include "SymTab/Indexer.h"
[c8dfcd3]36#include "SymTab/Autogen.h"
[71f4e4f]37#include "GenPoly/PolyMutator.h"
[b6fe7e6]38#include "GenPoly/DeclMutator.h"
[c2931ea]39#include "SynTree/AddStmtVisitor.h"
[f0121d7]40#include "CodeGen/GenType.h"  // for warning/error messages
[8bf784a]41#include "Tuples/Tuples.h"
[71f4e4f]42
[f0121d7]43bool ctordtorp = false; // print all debug
44bool ctorp = false; // print ctor debug
45bool cpctorp = false; // print copy ctor debug
46bool dtorp = false; // print dtor debug
[845cedc]47#define PRINT( text ) if ( ctordtorp ) { text }
[c2931ea]48#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
49#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
[845cedc]50
[71f4e4f]51namespace InitTweak {
52        namespace {
[31f379c]53                typedef std::unordered_map< Expression *, TypeSubstitution * > EnvMap;
[597db97]54                typedef std::unordered_map< int, int > UnqCount;
[31f379c]55
[62e5546]56                class InsertImplicitCalls final : public GenPoly::PolyMutator {
[c2931ea]57                public:
[adcc065]58                        /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
59                        /// function calls need their parameters to be copy constructed
[31f379c]60                        static void insert( std::list< Declaration * > & translationUnit, EnvMap & envMap );
[c2931ea]61
[31f379c]62                        InsertImplicitCalls( EnvMap & envMap ) : envMap( envMap ) {}
63                        typedef GenPoly::PolyMutator Parent;
64                        using Parent::mutate;
[62e5546]65                        virtual Expression * mutate( ApplicationExpr * appExpr ) override;
[31f379c]66                        virtual Expression * mutate( StmtExpr * stmtExpr ) override;
67
68                        // collects environments for relevant nodes
69                        EnvMap & envMap;
[c2931ea]70                };
71
[62e5546]72                class ResolveCopyCtors final : public SymTab::Indexer {
[c2931ea]73                public:
[adcc065]74                        /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
75                        /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
76                        /// arguments and return value temporaries
[597db97]77                        static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount );
[c2931ea]78
[141b786]79                        typedef SymTab::Indexer Parent;
80                        using Parent::visit;
81
[597db97]82                        ResolveCopyCtors( const EnvMap & envMap, UnqCount & unqCount ) : envMap( envMap ), unqCount( unqCount ) {}
[31f379c]83
[62e5546]84                        virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
[31f379c]85                        virtual void visit( UniqueExpr * unqExpr ) override;
86                        virtual void visit( StmtExpr * stmtExpr ) override;
[c2931ea]87
88                        /// create and resolve ctor/dtor expression: fname(var, [cpArg])
[65660bd]89                        Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
[c2931ea]90                        /// true if type does not need to be copy constructed to ensure correctness
[1132b62]91                        bool skipCopyConstruct( Type * type );
92                        void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
[092528b]93                        void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
[31f379c]94
[c2931ea]95                        TypeSubstitution * env;
[31f379c]96                        const EnvMap & envMap;
[597db97]97                        UnqCount & unqCount; // count the number of times each unique expr ID appears
[c2931ea]98                };
99
100                /// collects constructed object decls - used as a base class
101                class ObjDeclCollector : public AddStmtVisitor {
102                  public:
103                        typedef AddStmtVisitor Parent;
104                        using Parent::visit;
105                        typedef std::set< ObjectDecl * > ObjectSet;
[62e5546]106                        virtual void visit( CompoundStmt *compoundStmt ) override;
107                        virtual void visit( DeclStmt *stmt ) override;
[52c14b3]108
109                        // don't go into other functions
110                        virtual void visit( FunctionDecl *decl ) override {}
111
[c2931ea]112                  protected:
113                        ObjectSet curVars;
114                };
115
[6cf27a07]116                // debug
[c2931ea]117                struct printSet {
118                        typedef ObjDeclCollector::ObjectSet ObjectSet;
119                        printSet( const ObjectSet & objs ) : objs( objs ) {}
120                        const ObjectSet & objs;
121                };
122                std::ostream & operator<<( std::ostream & out, const printSet & set) {
123                        out << "{ ";
124                        for ( ObjectDecl * obj : set.objs ) {
125                                out << obj->get_name() << ", " ;
[adcc065]126                        } // for
[c2931ea]127                        out << " }";
128                        return out;
129                }
130
[62e5546]131                class LabelFinder final : public ObjDeclCollector {
[c2931ea]132                  public:
133                        typedef ObjDeclCollector Parent;
134                        typedef std::map< Label, ObjectSet > LabelMap;
135                        // map of Label -> live variables at that label
136                        LabelMap vars;
137
138                        void handleStmt( Statement * stmt );
139
140                        // xxx - This needs to be done better.
[adcc065]141                        // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
142                        // expressions, all statements, etc.)  important to have this to provide a single entry point so that as new
143                        // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
144                        // every specialized class knows about every new kind of statement that might be added.
[62e5546]145                        using Parent::visit;
146                        virtual void visit( CompoundStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
147                        virtual void visit( ExprStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
148                        virtual void visit( AsmStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
149                        virtual void visit( IfStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
150                        virtual void visit( WhileStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
151                        virtual void visit( ForStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
152                        virtual void visit( SwitchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
153                        virtual void visit( CaseStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
154                        virtual void visit( BranchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
155                        virtual void visit( ReturnStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
156                        virtual void visit( TryStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
157                        virtual void visit( CatchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
158                        virtual void visit( FinallyStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
159                        virtual void visit( NullStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
160                        virtual void visit( DeclStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
161                        virtual void visit( ImplicitCtorDtorStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
[c2931ea]162                };
163
[62e5546]164                class InsertDtors final : public ObjDeclCollector {
[c2931ea]165                public:
[adcc065]166                        /// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
167                        /// (currently by FixInit)
[c2931ea]168                        static void insert( std::list< Declaration * > & translationUnit );
169
170                        typedef ObjDeclCollector Parent;
171                        typedef std::list< ObjectDecl * > OrderedDecls;
172                        typedef std::list< OrderedDecls > OrderedDeclsStack;
173
[52c14b3]174                        InsertDtors( LabelFinder & finder ) : finder( finder ), labelVars( finder.vars ) {}
[c2931ea]175
[62e5546]176                        using Parent::visit;
177
178                        virtual void visit( ObjectDecl * objDecl ) override;
[52c14b3]179                        virtual void visit( FunctionDecl * funcDecl ) override;
[c2931ea]180
[62e5546]181                        virtual void visit( CompoundStmt * compoundStmt ) override;
182                        virtual void visit( ReturnStmt * returnStmt ) override;
183                        virtual void visit( BranchStmt * stmt ) override;
[c2931ea]184                private:
185                        void handleGoto( BranchStmt * stmt );
186
[52c14b3]187                        LabelFinder & finder;
[c2931ea]188                        LabelFinder::LabelMap & labelVars;
189                        OrderedDeclsStack reverseDeclOrder;
190                };
191
[62e5546]192                class FixInit final : public GenPoly::PolyMutator {
[c2931ea]193                  public:
194                        /// expand each object declaration to use its constructor after it is declared.
195                        static void fixInitializers( std::list< Declaration * > &translationUnit );
196
[31f379c]197                        typedef GenPoly::PolyMutator Parent;
198                        using Parent::mutate;
[62e5546]199                        virtual DeclarationWithType * mutate( ObjectDecl *objDecl ) override;
[72e9222]200
201                        std::list< Declaration * > staticDtorDecls;
[c2931ea]202                };
203
[62e5546]204                class FixCopyCtors final : public GenPoly::PolyMutator {
[c2931ea]205                  public:
[597db97]206                        FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
[adcc065]207                        /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
208                        /// and destructors
[597db97]209                        static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
[c2931ea]210
[31f379c]211                        typedef GenPoly::PolyMutator Parent;
212                        using Parent::mutate;
[62e5546]213                        virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
[b726084]214                        virtual Expression * mutate( UniqueExpr * unqExpr ) override;
[31f379c]215                        virtual Expression * mutate( StmtExpr * stmtExpr ) override;
[597db97]216
217                        UnqCount & unqCount;
[c2931ea]218                };
[79970ed]219
[62e5546]220                class GenStructMemberCalls final : public SymTab::Indexer {
[79970ed]221                  public:
[c8dfcd3]222                        typedef Indexer Parent;
223                        /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
224                        /// for any member that is missing a corresponding ctor/dtor call.
225                        /// error if a member is used before constructed
226                        static void generate( std::list< Declaration * > & translationUnit );
[79970ed]227
[62e5546]228                        using Parent::visit;
229
230                        virtual void visit( FunctionDecl * funcDecl ) override;
[79970ed]231
[62e5546]232                        virtual void visit( MemberExpr * memberExpr ) override;
233                        virtual void visit( ApplicationExpr * appExpr ) override;
[79970ed]234
[3906301]235                        SemanticError errors;
[79970ed]236                  private:
237                        void handleFirstParam( Expression * firstParam );
[3906301]238                        template< typename... Params >
[64ac636]239                        void emit( CodeLocation, const Params &... params );
[79970ed]240
241                        FunctionDecl * function = 0;
[64ac636]242                        std::set< DeclarationWithType * > unhandled;
243                        std::map< DeclarationWithType *, CodeLocation > usedUninit;
[79970ed]244                        ObjectDecl * thisParam = 0;
[c8dfcd3]245                        bool isCtor = false; // true if current function is a constructor
[44f6341]246                        StructDecl * structDecl = 0;
[c8dfcd3]247                };
248
249                // very simple resolver-like mutator class - used to
250                // resolve UntypedExprs that are found within newly
251                // generated constructor/destructor calls
[62e5546]252                class MutatingResolver final : public Mutator {
[c8dfcd3]253                  public:
254                        MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
255
[62e5546]256                        using Mutator::mutate;
257                        virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
258                        virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
[c8dfcd3]259
[62e5546]260                  private:
[c8dfcd3]261                        SymTab::Indexer & indexer;
[79970ed]262                };
[b6fe7e6]263
[62e5546]264                class FixCtorExprs final : public GenPoly::DeclMutator {
[b6fe7e6]265                  public:
266                        /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
267                        static void fix( std::list< Declaration * > & translationUnit );
268
[62e5546]269                        using GenPoly::DeclMutator::mutate;
270                        virtual Expression * mutate( ConstructorExpr * ctorExpr ) override;
[b6fe7e6]271                };
[c2931ea]272        } // namespace
[db4ecc5]273
[6cf27a07]274        void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
275                // fixes ConstructorInit for global variables. should happen before fixInitializers.
276                InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
277
[31f379c]278                EnvMap envMap;
[597db97]279                UnqCount unqCount;
[b6fe7e6]280
[31f379c]281                InsertImplicitCalls::insert( translationUnit, envMap );
[597db97]282                ResolveCopyCtors::resolveImplicitCalls( translationUnit, envMap, unqCount );
[c2931ea]283                InsertDtors::insert( translationUnit );
[71f4e4f]284                FixInit::fixInitializers( translationUnit );
[c2931ea]285
[db4ecc5]286                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
[597db97]287                FixCopyCtors::fixCopyCtors( translationUnit, unqCount );
[79970ed]288
[c8dfcd3]289                GenStructMemberCalls::generate( translationUnit );
[b6fe7e6]290                // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
291                // hack in the way untyped assignments are generated, where the first argument cannot have
292                // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
293                // Thus such assignment exprs must never pushed through expression resolution (and thus should
294                // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
295                // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
296                // don't look right, and a member can be constructed more than once.
297                FixCtorExprs::fix( translationUnit );
[db4ecc5]298        }
299
[c2931ea]300        namespace {
[31f379c]301                void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit, EnvMap & envMap ) {
302                        InsertImplicitCalls inserter( envMap );
[c2931ea]303                        mutateAll( translationUnit, inserter );
304                }
[db4ecc5]305
[597db97]306                void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, const EnvMap & envMap, UnqCount & unqCount ) {
307                        ResolveCopyCtors resolver( envMap, unqCount );
[c2931ea]308                        acceptAll( translationUnit, resolver );
309                }
[71f4e4f]310
[c2931ea]311                void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
312                        FixInit fixer;
[72e9222]313
314                        // can't use mutateAll, because need to insert declarations at top-level
315                        // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
316                        SemanticError errors;
317                        for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
318                                try {
319                                        *i = maybeMutate( *i, fixer );
[f9cebb5]320                                        translationUnit.splice( i, fixer.staticDtorDecls );
[72e9222]321                                } catch( SemanticError &e ) {
[138e29e]322                                        e.set_location( (*i)->location );
[72e9222]323                                        errors.append( e );
324                                } // try
325                        } // for
326                        if ( ! errors.isEmpty() ) {
327                                throw errors;
328                        } // if
[c2931ea]329                }
[71f4e4f]330
[c2931ea]331                void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
332                        LabelFinder finder;
333                        InsertDtors inserter( finder );
334                        acceptAll( translationUnit, inserter );
335                }
336
[597db97]337                void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
338                        FixCopyCtors fixer( unqCount );
[c2931ea]339                        mutateAll( translationUnit, fixer );
340                }
[db4ecc5]341
[c8dfcd3]342                void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
343                        GenStructMemberCalls warner;
344                        acceptAll( translationUnit, warner );
[79970ed]345                }
346
[b6fe7e6]347                void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
348                        FixCtorExprs fixer;
349                        fixer.mutateDeclarationList( translationUnit );
350                }
351
[c2931ea]352                Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
[31f379c]353                        appExpr = dynamic_cast< ApplicationExpr * >( Parent::mutate( appExpr ) );
[c2931ea]354                        assert( appExpr );
355
356                        if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
[9a063c8]357                                if ( LinkageSpec::isBuiltin( function->get_var()->get_linkage() ) ) {
[c2931ea]358                                        // optimization: don't need to copy construct in order to call intrinsic functions
359                                        return appExpr;
360                                } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
361                                        FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
362                                        assert( ftype );
[a28bc02]363                                        if ( isConstructor( funcDecl->get_name() ) && ftype->get_parameters().size() == 2 ) {
[c2931ea]364                                                Type * t1 = ftype->get_parameters().front()->get_type();
365                                                Type * t2 = ftype->get_parameters().back()->get_type();
[31f379c]366                                                PointerType * ptrType = safe_dynamic_cast< PointerType * > ( t1 );
[c2931ea]367
368                                                if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
[a28bc02]369                                                        // optimization: don't need to copy construct in order to call a copy constructor
[c2931ea]370                                                        return appExpr;
[adcc065]371                                                } // if
[79970ed]372                                        } else if ( isDestructor( funcDecl->get_name() ) ) {
[c2931ea]373                                                // correctness: never copy construct arguments to a destructor
[845cedc]374                                                return appExpr;
[adcc065]375                                        } // if
376                                } // if
377                        } // if
[c2931ea]378                        CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
379
380                        // wrap each function call so that it is easy to identify nodes that have to be copy constructed
381                        ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
[31f379c]382                        // save the type substitution into the envMap so that it is easy to find.
[c2931ea]383                        // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
384                        // The substitution is needed to obtain the type of temporary variables so that copy constructor
385                        // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
386                        // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
387                        // saves the environment, or compute the types of temporaries here, but it's much simpler to
388                        // save the environment here, and more cohesive to compute temporary variables and resolve copy
389                        // constructor calls together.
390                        assert( env );
[31f379c]391                        envMap[expr] = env;
[c2931ea]392                        return expr;
[db4ecc5]393                }
394
[31f379c]395                Expression * InsertImplicitCalls::mutate( StmtExpr * stmtExpr ) {
396                        assert( env );
397                        envMap[stmtExpr] = env;
398                        return Parent::mutate( stmtExpr );
399                }
400
[c2931ea]401                bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
[8bf784a]402                        return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type ) || Tuples::isTtype( type );
[c2931ea]403                }
404
[65660bd]405                Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
[c2931ea]406                        assert( var );
[092528b]407                        // arrays are not copy constructed, so this should always be an ExprStmt
408                        ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
409                        ExprStmt * exprStmt = safe_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
410                        Expression * untyped = exprStmt->get_expr();
[c2931ea]411
412                        // resolve copy constructor
[adcc065]413                        // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
414                        // (VariableExpr and already resolved expression)
[c2931ea]415                        CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
[65660bd]416                        Expression * resolved = ResolvExpr::findVoidExpression( untyped, *this );
417                        assert( resolved );
[c2931ea]418                        if ( resolved->get_env() ) {
[31f379c]419                                // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
[c2931ea]420                                env->add( *resolved->get_env() );
[31f379c]421                                delete resolved->get_env();
422                                resolved->set_env( nullptr );
[adcc065]423                        } // if
[cf18eea]424
[092528b]425                        delete stmt;
[c2931ea]426                        return resolved;
[540de412]427                }
[db4ecc5]428
[1132b62]429                void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
[c2931ea]430                        static UniqueName tempNamer("_tmp_cp");
[31f379c]431                        assert( env );
432                        CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
[1132b62]433                        assert( arg->has_result() );
434                        Type * result = arg->get_result();
435                        if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
436
437                        // type may involve type variables, so apply type substitution to get temporary variable's actual type
438                        result = result->clone();
[31f379c]439                        env->apply( result );
[68fe077a]440                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]441                        tmp->get_type()->set_const( false );
[1132b62]442
443                        // create and resolve copy constructor
444                        CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
[65660bd]445                        Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg );
446
447                        if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) {
448                                // if the chosen constructor is intrinsic, the copy is unnecessary, so
449                                // don't create the temporary and don't call the copy constructor
450                                VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
451                                assert( function );
452                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return;
453                        }
454
455                        // replace argument to function call with temporary
456                        arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
457                        impCpCtorExpr->get_tempDecls().push_back( tmp );
458                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
[1132b62]459                }
[c2931ea]460
[092528b]461                void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
462                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
[1132b62]463                }
464
465                void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
[c2931ea]466                        CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
[141b786]467                        Parent::visit( impCpCtorExpr );
[31f379c]468                        env = envMap.at(impCpCtorExpr);
469                        assert( env );
[c2931ea]470
471                        ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
472
473                        // take each argument and attempt to copy construct it.
474                        for ( Expression * & arg : appExpr->get_args() ) {
[1132b62]475                                copyConstructArg( arg, impCpCtorExpr );
[adcc065]476                        } // for
[db4ecc5]477
[adcc065]478                        // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
479                        // initialized with the return value and is destructed later
[31f379c]480                        // xxx - handle named return values?
[906e24d]481                        Type * result = appExpr->get_result();
482                        if ( ! result->isVoid() ) {
[1132b62]483                                static UniqueName retNamer("_tmp_cp_ret");
[c2931ea]484                                result = result->clone();
[31f379c]485                                env->apply( result );
[68fe077a]486                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]487                                ret->get_type()->set_const( false );
[c2931ea]488                                impCpCtorExpr->get_returnDecls().push_back( ret );
489                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
[615a096]490                                if ( ! result->get_lvalue() ) {
[dc86541]491                                        // destructing lvalue returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
[092528b]492                                        destructRet( ret, impCpCtorExpr );
[dc86541]493                                }
[adcc065]494                        } // for
[c2931ea]495                        CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
[db4ecc5]496                }
497
[31f379c]498                void ResolveCopyCtors::visit( StmtExpr * stmtExpr ) {
499                        Parent::visit( stmtExpr );
500                        env = envMap.at(stmtExpr);
501                        assert( stmtExpr->get_result() );
502                        Type * result = stmtExpr->get_result();
503                        if ( ! result->isVoid() ) {
504                                static UniqueName retNamer("_tmp_stmtexpr_ret");
505
506                                // create variable that will hold the result of the stmt expr
507                                result = result->clone();
508                                env->apply( result );
[68fe077a]509                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), Type::StorageClasses(), LinkageSpec::C, 0, result, 0 );
[615a096]510                                ret->get_type()->set_const( false );
[31f379c]511                                stmtExpr->get_returnDecls().push_front( ret );
512
513                                // must have a non-empty body, otherwise it wouldn't have a result
514                                CompoundStmt * body = stmtExpr->get_statements();
515                                assert( ! body->get_kids().empty() );
516                                // must be an ExprStmt, otherwise it wouldn't have a result
517                                ExprStmt * last = safe_dynamic_cast< ExprStmt * >( body->get_kids().back() );
518                                last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
519
[092528b]520                                stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
[31f379c]521                        } // if
522
523                }
524
[141b786]525                void ResolveCopyCtors::visit( UniqueExpr * unqExpr ) {
526                        static std::unordered_set< int > vars;
[597db97]527                        unqCount[ unqExpr->get_id() ]++;  // count the number of unique expressions for each ID
[141b786]528                        if ( vars.count( unqExpr->get_id() ) ) {
529                                // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
530                                return;
531                        }
532
533                        Parent::visit( unqExpr );
534                        // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
535                        assert( unqExpr->get_result() );
536                        if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) {
537                                // note the variable used as the result from the call
538                                assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 );
539                                unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) );
540                        } else {
541                                // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
[14a33790]542                                unqExpr->set_object( new ObjectDecl( toString("_unq", unqExpr->get_id()), Type::StorageClasses(), LinkageSpec::C, nullptr, unqExpr->get_result()->clone(), nullptr ) );
[141b786]543                                unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
544                        }
545                        vars.insert( unqExpr->get_id() );
546                }
547
[c2931ea]548                Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
549                        CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
550
[31f379c]551                        impCpCtorExpr = safe_dynamic_cast< ImplicitCopyCtorExpr * >( Parent::mutate( impCpCtorExpr ) );
[c2931ea]552                        std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
553                        std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
554                        std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
[845cedc]555
[c2931ea]556                        // add all temporary declarations and their constructors
557                        for ( ObjectDecl * obj : tempDecls ) {
558                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]559                        } // for
[c2931ea]560                        for ( ObjectDecl * obj : returnDecls ) {
561                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]562                        } // for
[db4ecc5]563
[c2931ea]564                        // add destructors after current statement
565                        for ( Expression * dtor : dtors ) {
566                                stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
[adcc065]567                        } // for
[db4ecc5]568
[c2931ea]569                        // xxx - update to work with multiple return values
570                        ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
571                        Expression * callExpr = impCpCtorExpr->get_callExpr();
572
573                        CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
574
575                        // detach fields from wrapper node so that it can be deleted without deleting too much
576                        dtors.clear();
577                        tempDecls.clear();
578                        returnDecls.clear();
579                        impCpCtorExpr->set_callExpr( NULL );
580                        impCpCtorExpr->set_env( NULL );
581                        delete impCpCtorExpr;
582
583                        if ( returnDecl ) {
584                                UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
585                                assign->get_args().push_back( new VariableExpr( returnDecl ) );
586                                assign->get_args().push_back( callExpr );
587                                // know the result type of the assignment is the type of the LHS (minus the pointer), so
588                                // add that onto the assignment expression so that later steps have the necessary information
[906e24d]589                                assign->set_result( returnDecl->get_type()->clone() );
[c2931ea]590
591                                Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
[615a096]592                                if ( callExpr->get_result()->get_lvalue() ) {
[adcc065]593                                        // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
594                                        // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
595                                        // type of the return temporary from T to T* to properly capture the return value. Then dereference
596                                        // the result of the comma expression, since the lvalue returning call was originally wrapped with
597                                        // an AddressExpr.  Effectively, this turns
[c2931ea]598                                        //   lvalue T f();
[b3b2077]599                                        //   &*f();
[c2931ea]600                                        // into
[b3b2077]601                                        //   T * f();
[c2931ea]602                                        //   T * tmp_cp_retN;
[b3b2077]603                                        //   &*(tmp_cp_retN = &*f(), tmp_cp_retN);              // the first * and second & are generated here
[c2931ea]604                                        // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
605                                        assign->get_args().back() = new AddressExpr( assign->get_args().back() );
606
607                                        returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
[b3b2077]608                                        retExpr->set_result( new PointerType( Type::Qualifiers(), retExpr->get_result() ) );
609                                        retExpr = UntypedExpr::createDeref( retExpr );
[adcc065]610                                } // if
[31f379c]611                                // move env from callExpr to retExpr
612                                retExpr->set_env( callExpr->get_env() );
613                                callExpr->set_env( nullptr );
[c2931ea]614                                return retExpr;
615                        } else {
616                                return callExpr;
[adcc065]617                        } // if
[4ffdd63]618                }
[c2931ea]619
[31f379c]620                Expression * FixCopyCtors::mutate( StmtExpr * stmtExpr ) {
621                        stmtExpr = safe_dynamic_cast< StmtExpr * >( Parent::mutate( stmtExpr ) );
622                        assert( stmtExpr->get_result() );
623                        Type * result = stmtExpr->get_result();
624                        if ( ! result->isVoid() ) {
625                                for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
626                                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
627                                } // for
628                                // add destructors after current statement
629                                for ( Expression * dtor : stmtExpr->get_dtors() ) {
630                                        stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
631                                } // for
632                                // must have a non-empty body, otherwise it wouldn't have a result
633                                CompoundStmt * body = stmtExpr->get_statements();
634                                assert( ! body->get_kids().empty() );
635                                assert( ! stmtExpr->get_returnDecls().empty() );
636                                body->get_kids().push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
[a28bc02]637                                stmtExpr->get_returnDecls().clear();
638                                stmtExpr->get_dtors().clear();
[31f379c]639                        }
[a28bc02]640                        assert( stmtExpr->get_returnDecls().empty() );
641                        assert( stmtExpr->get_dtors().empty() );
[31f379c]642                        return stmtExpr;
643                }
644
[141b786]645                Expression * FixCopyCtors::mutate( UniqueExpr * unqExpr ) {
[597db97]646                        unqCount[ unqExpr->get_id() ]--;
647                        static std::unordered_map< int, std::list< Statement * > > dtors;
[141b786]648                        static std::unordered_map< int, UniqueExpr * > unqMap;
649                        static std::unordered_set< int > addDeref;
650                        // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
651                        if ( unqMap.count( unqExpr->get_id() ) ) {
652                                // take data from other UniqueExpr to ensure consistency
653                                delete unqExpr->get_expr();
654                                unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
655                                delete unqExpr->get_result();
656                                unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
[597db97]657                                if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
658                                        stmtsToAdd.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
659                                }
[141b786]660                                if ( addDeref.count( unqExpr->get_id() ) ) {
661                                        // other UniqueExpr was dereferenced because it was an lvalue return, so this one should be too
662                                        return UntypedExpr::createDeref( unqExpr );
663                                }
664                                return unqExpr;
665                        }
[597db97]666                        FixCopyCtors fixer( unqCount );
667                        unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
668                        stmtsToAdd.splice( stmtsToAdd.end(), fixer.stmtsToAdd );
[141b786]669                        unqMap[unqExpr->get_id()] = unqExpr;
[a28bc02]670                        if ( unqCount[ unqExpr->get_id() ] == 0 ) {  // insert destructor after the last use of the unique expression
671                                stmtsToAdd.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
672                        } else { // remember dtors for last instance of unique expr
673                                dtors[ unqExpr->get_id() ] = fixer.stmtsToAddAfter;
674                        }
[141b786]675                        if ( UntypedExpr * deref = dynamic_cast< UntypedExpr * >( unqExpr->get_expr() ) ) {
676                                // unique expression is now a dereference, because the inner expression is an lvalue returning function call.
677                                // Normalize the expression by dereferencing the unique expression, rather than the inner expression
678                                // (i.e. move the dereference out a level)
679                                assert( getFunctionName( deref ) == "*?" );
680                                unqExpr->set_expr( getCallArg( deref, 0 ) );
681                                getCallArg( deref, 0 ) = unqExpr;
682                                addDeref.insert( unqExpr->get_id() );
683                                return deref;
684                        }
685                        return unqExpr;
686                }
687
[c2931ea]688                DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
[adcc065]689                        // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
690                        // is removed from the ObjectDecl
[31f379c]691                        objDecl = dynamic_cast< ObjectDecl * >( Parent::mutate( objDecl ) );
[c2931ea]692                        if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
693                                // a decision should have been made by the resolver, so ctor and init are not both non-NULL
694                                assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
695                                if ( Statement * ctor = ctorInit->get_ctor() ) {
[08d5507b]696                                        if ( objDecl->get_storageClasses().is_static ) {
[72e9222]697                                                // originally wanted to take advantage of gcc nested functions, but
[f9cebb5]698                                                // we get memory errors with this approach. To remedy this, the static
699                                                // variable is hoisted when the destructor needs to be called.
[72e9222]700                                                //
[c2931ea]701                                                // generate:
[f9cebb5]702                                                // static T __objName_static_varN;
[72e9222]703                                                // void __objName_dtor_atexitN() {
[f9cebb5]704                                                //   __dtor__...;
[72e9222]705                                                // }
706                                                // int f(...) {
707                                                //   ...
708                                                //   static bool __objName_uninitialized = true;
709                                                //   if (__objName_uninitialized) {
710                                                //     __ctor(__objName);
711                                                //     __objName_uninitialized = false;
[f9cebb5]712                                                //     atexit(__objName_dtor_atexitN);
[c2931ea]713                                                //   }
[72e9222]714                                                //   ...
[c2931ea]715                                                // }
716
[72e9222]717                                                static UniqueName dtorCallerNamer( "_dtor_atexit" );
718
719                                                // static bool __objName_uninitialized = true
[c2931ea]720                                                BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
721                                                SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
[68fe077a]722                                                ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
[c2931ea]723                                                isUninitializedVar->fixUniqueId();
724
725                                                // __objName_uninitialized = false;
726                                                UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
727                                                setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
728                                                setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
729
730                                                // generate body of if
731                                                CompoundStmt * initStmts = new CompoundStmt( noLabels );
732                                                std::list< Statement * > & body = initStmts->get_kids();
733                                                body.push_back( ctor );
734                                                body.push_back( new ExprStmt( noLabels, setTrue ) );
735
736                                                // put it all together
737                                                IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
738                                                stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
739                                                stmtsToAddAfter.push_back( ifStmt );
[72e9222]740
[a4dd728]741                                                Statement * dtor = ctorInit->get_dtor();
742                                                objDecl->set_init( NULL );
743                                                ctorInit->set_ctor( NULL );
744                                                ctorInit->set_dtor( nullptr );
745                                                if ( dtor ) {
[f9cebb5]746                                                        // if the object has a non-trivial destructor, have to
747                                                        // hoist it and the object into the global space and
748                                                        // call the destructor function with atexit.
749
[a4dd728]750                                                        Statement * dtorStmt = dtor->clone();
[f9cebb5]751
752                                                        // void __objName_dtor_atexitN(...) {...}
[68fe077a]753                                                        FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
[f9cebb5]754                                                        dtorCaller->fixUniqueId();
[c8dfcd3]755                                                        dtorCaller->get_statements()->push_back( dtorStmt );
[f9cebb5]756
757                                                        // atexit(dtor_atexit);
758                                                        UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
759                                                        callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
760
761                                                        body.push_back( new ExprStmt( noLabels, callAtexit ) );
762
763                                                        // hoist variable and dtor caller decls to list of decls that will be added into global scope
764                                                        staticDtorDecls.push_back( objDecl );
765                                                        staticDtorDecls.push_back( dtorCaller );
766
767                                                        // need to rename object uniquely since it now appears
768                                                        // at global scope and there could be multiple function-scoped
769                                                        // static variables with the same name in different functions.
[c8dfcd3]770                                                        // Note: it isn't sufficient to modify only the mangleName, because
771                                                        // then subsequent Indexer passes can choke on seeing the object's name
772                                                        // if another object has the same name and type. An unfortunate side-effect
773                                                        // of renaming the object is that subsequent NameExprs may fail to resolve,
774                                                        // but there shouldn't be any remaining past this point.
[f9cebb5]775                                                        static UniqueName staticNamer( "_static_var" );
[c8dfcd3]776                                                        objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
777                                                        objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
[f9cebb5]778
779                                                        // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
780                                                        // create a new object which is never used
781                                                        static UniqueName dummyNamer( "_dummy" );
[68fe077a]782                                                        ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
[a4dd728]783                                                        delete ctorInit;
[f9cebb5]784                                                        return dummy;
785                                                }
[c2931ea]786                                        } else {
[233e4d9]787                                                ImplicitCtorDtorStmt * implicit = safe_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
788                                                ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->get_callStmt() );
789                                                ApplicationExpr * ctorCall = nullptr;
790                                                if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->get_expr() )) && ctorCall->get_args().size() == 2 ) {
791                                                        // clean up intrinsic copy constructor calls by making them into SingleInits
792                                                        objDecl->set_init( new SingleInit( ctorCall->get_args().back() ) );
793                                                        ctorCall->get_args().pop_back();
794                                                } else {
795                                                        stmtsToAddAfter.push_back( ctor );
796                                                        objDecl->set_init( NULL );
797                                                        ctorInit->set_ctor( NULL );
798                                                }
[adcc065]799                                        } // if
[c2931ea]800                                } else if ( Initializer * init = ctorInit->get_init() ) {
801                                        objDecl->set_init( init );
802                                        ctorInit->set_init( NULL );
803                                } else {
804                                        // no constructor and no initializer, which is okay
805                                        objDecl->set_init( NULL );
[adcc065]806                                } // if
[c2931ea]807                                delete ctorInit;
[adcc065]808                        } // if
[c2931ea]809                        return objDecl;
[db4ecc5]810                }
811
[52c14b3]812                void ObjDeclCollector::visit( CompoundStmt * compoundStmt ) {
[c2931ea]813                        std::set< ObjectDecl * > prevVars = curVars;
814                        Parent::visit( compoundStmt );
815                        curVars = prevVars;
[db4ecc5]816                }
817
[52c14b3]818                void ObjDeclCollector::visit( DeclStmt * stmt ) {
[4b2589a]819                        // keep track of all variables currently in scope
[c2931ea]820                        if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
821                                curVars.insert( objDecl );
[adcc065]822                        } // if
[e39aa0f]823                        Parent::visit( stmt );
[db4ecc5]824                }
825
[c2931ea]826                void LabelFinder::handleStmt( Statement * stmt ) {
[4b2589a]827                        // for each label, remember the variables in scope at that label.
[c2931ea]828                        for ( Label l : stmt->get_labels() ) {
829                                vars[l] = curVars;
[adcc065]830                        } // for
[71f4e4f]831                }
[f1e012b]832
[ec79847]833                template<typename Iterator, typename OutputIterator>
834                void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
835                        for ( Iterator it = begin ; it != end ; ++it ) {
[adcc065]836                                // extract destructor statement from the object decl and insert it into the output. Note that this is
837                                // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
838                                // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
839                                // contain side effects.
[c2931ea]840                                ObjectDecl * objDecl = *it;
841                                ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
842                                assert( ctorInit && ctorInit->get_dtor() );
843                                *out++ = ctorInit->get_dtor()->clone();
[adcc065]844                        } // for
[f1e012b]845                }
[39786813]846
[c2931ea]847                void InsertDtors::visit( ObjectDecl * objDecl ) {
848                        // remember non-static destructed objects so that their destructors can be inserted later
[08d5507b]849                        if ( ! objDecl->get_storageClasses().is_static ) {
[c2931ea]850                                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
851                                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
852                                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
853                                        Statement * dtor = ctorInit->get_dtor();
[f9cebb5]854                                        if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
[c2931ea]855                                                // don't need to call intrinsic dtor, because it does nothing, but
856                                                // non-intrinsic dtors must be called
857                                                reverseDeclOrder.front().push_front( objDecl );
[adcc065]858                                        } // if
859                                } // if
860                        } // if
[c2931ea]861                        Parent::visit( objDecl );
862                }
[39786813]863
[52c14b3]864                template< typename Visitor >
865                void handleFuncDecl( FunctionDecl * funcDecl, Visitor & visitor ) {
866                        maybeAccept( funcDecl->get_functionType(), visitor );
867                        maybeAccept( funcDecl->get_statements(), visitor );
868                }
869
870                void InsertDtors::visit( FunctionDecl * funcDecl ) {
871                        // each function needs to have its own set of labels
872                        ValueGuard< LabelFinder::LabelMap > oldLabels( labelVars );
873                        labelVars.clear();
874                        handleFuncDecl( funcDecl, finder );
875
876                        // all labels for this function have been collected, insert destructors as appropriate.
877                        // can't be Parent::mutate, because ObjDeclCollector bottoms out on FunctionDecl
878                        handleFuncDecl( funcDecl, *this );
879                }
880
[c2931ea]881                void InsertDtors::visit( CompoundStmt * compoundStmt ) {
[adcc065]882                        // visit statements - this will also populate reverseDeclOrder list.  don't want to dump all destructors
883                        // when block is left, just the destructors associated with variables defined in this block, so push a new
884                        // list to the top of the stack so that we can differentiate scopes
[c2931ea]885                        reverseDeclOrder.push_front( OrderedDecls() );
886                        Parent::visit( compoundStmt );
[39786813]887
[4b2589a]888                        // add destructors for the current scope that we're exiting
[c2931ea]889                        std::list< Statement * > & statements = compoundStmt->get_kids();
890                        insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
891                        reverseDeclOrder.pop_front();
[39786813]892                }
893
[c2931ea]894                void InsertDtors::visit( ReturnStmt * returnStmt ) {
[4b2589a]895                        // return exits all scopes, so dump destructors for all scopes
[c2931ea]896                        for ( OrderedDecls & od : reverseDeclOrder ) {
897                                insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
[adcc065]898                        } // for
[39786813]899                }
[f1e012b]900
[adcc065]901                // Handle break/continue/goto in the same manner as C++.  Basic idea: any objects that are in scope at the
902                // BranchStmt but not at the labelled (target) statement must be destructed.  If there are any objects in scope
903                // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
904                // of the error.  See C++ Reference 6.6 Jump Statements for details.
[c2931ea]905                void InsertDtors::handleGoto( BranchStmt * stmt ) {
[e39aa0f]906                        assert( stmt->get_target() != "" && "BranchStmt missing a label" );
[c2931ea]907                        // S_L = lvars = set of objects in scope at label definition
908                        // S_G = curVars = set of objects in scope at goto statement
909                        ObjectSet & lvars = labelVars[ stmt->get_target() ];
910
911                        DTOR_PRINT(
912                                std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
913                                std::cerr << "S_G = " << printSet( curVars ) << std::endl;
914                                std::cerr << "S_L = " << printSet( lvars ) << std::endl;
915                        )
916
917                        ObjectSet diff;
918                        // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
919                        std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
920                        DTOR_PRINT(
921                                std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
922                        )
923                        if ( ! diff.empty() ) {
924                                throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
[adcc065]925                        } // if
[c2931ea]926                        // S_G-S_L results in set of objects that must be destructed
927                        diff.clear();
928                        std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
929                        DTOR_PRINT(
930                                std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
931                        )
932                        if ( ! diff.empty() ) {
933                                // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
934                                OrderedDecls ordered;
935                                for ( OrderedDecls & rdo : reverseDeclOrder ) {
936                                        // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
937                                        copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
[adcc065]938                                } // for
[c2931ea]939                                insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
[adcc065]940                        } // if
[c2931ea]941                }
[39786813]942
[c2931ea]943                void InsertDtors::visit( BranchStmt * stmt ) {
944                        switch( stmt->get_type() ) {
[adcc065]945                          case BranchStmt::Continue:
946                          case BranchStmt::Break:
947                                // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
948                                // always be empty), but it serves as a small sanity check.
949                          case BranchStmt::Goto:
950                                handleGoto( stmt );
951                                break;
952                          default:
953                                assert( false );
954                        } // switch
[c2931ea]955                }
[79970ed]956
957                bool checkWarnings( FunctionDecl * funcDecl ) {
958                        // only check for warnings if the current function is a user-defined
959                        // constructor or destructor
960                        if ( ! funcDecl ) return false;
961                        if ( ! funcDecl->get_statements() ) return false;
962                        return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
963                }
964
[c8dfcd3]965                void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
966                        ValueGuard< FunctionDecl * > oldFunction( funcDecl );
967                        ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
[64ac636]968                        ValueGuard< std::map< DeclarationWithType *, CodeLocation > > oldUsedUninit( usedUninit );
[c8dfcd3]969                        ValueGuard< ObjectDecl * > oldThisParam( thisParam );
970                        ValueGuard< bool > oldIsCtor( isCtor );
[44f6341]971                        ValueGuard< StructDecl * > oldStructDecl( structDecl );
[64ac636]972                        errors = SemanticError();  // clear previous errors
[c8dfcd3]973
974                        // need to start with fresh sets
975                        unhandled.clear();
976                        usedUninit.clear();
[79970ed]977
978                        function = funcDecl;
[c8dfcd3]979                        isCtor = isConstructor( function->get_name() );
980                        if ( checkWarnings( function ) ) {
981                                FunctionType * type = function->get_functionType();
[79970ed]982                                assert( ! type->get_parameters().empty() );
983                                thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
984                                PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
985                                StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
986                                if ( structType ) {
[44f6341]987                                        structDecl = structType->get_baseStruct();
[79970ed]988                                        for ( Declaration * member : structDecl->get_members() ) {
989                                                if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
990                                                        // record all of the struct type's members that need to be constructed or
991                                                        // destructed by the end of the function
992                                                        unhandled.insert( field );
993                                                }
994                                        }
995                                }
996                        }
[c8dfcd3]997                        Parent::visit( function );
998
999                        // remove the unhandled objects from usedUninit, because a call is inserted
1000                        // to handle them - only objects that are later constructed are used uninitialized.
[64ac636]1001                        std::map< DeclarationWithType *, CodeLocation > diff;
1002                        // need the comparator since usedUninit and unhandled have different types
1003                        struct comp_t {
1004                                typedef decltype(usedUninit)::value_type usedUninit_t;
1005                                typedef decltype(unhandled)::value_type unhandled_t;
1006                                bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
1007                                bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
1008                        } comp;
1009                        std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
1010                        for ( auto p : diff ) {
1011                                DeclarationWithType * member = p.first;
1012                                CodeLocation loc = p.second;
1013                                // xxx - make error message better by also tracking the location that the object is constructed at?
1014                                emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" );
[79970ed]1015                        }
1016
[c8dfcd3]1017                        if ( ! unhandled.empty() ) {
1018                                // need to explicitly re-add function parameters in order to resolve copy constructors
1019                                enterScope();
[b16898e]1020                                maybeAccept( function->get_functionType(), *this );
[44f6341]1021
1022                                // need to iterate through members in reverse in order for
1023                                // ctor/dtor statements to come out in the right order
[1ba88a0]1024                                for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
[44f6341]1025                                        DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
1026                                        // skip non-DWT members
1027                                        if ( ! field ) continue;
1028                                        // skip handled members
1029                                        if ( ! unhandled.count( field ) ) continue;
1030
1031                                        // insert and resolve default/copy constructor call for each field that's unhandled
[c8dfcd3]1032                                        std::list< Statement * > stmt;
[d9fa60a]1033                                        UntypedExpr * deref = UntypedExpr::createDeref( new VariableExpr( thisParam ) );
[4d4882a]1034
1035                                        Expression * arg2 = 0;
1036                                        if ( isCopyConstructor( function ) ) {
[44f6341]1037                                                // if copy ctor, need to pass second-param-of-this-function.field
[4d4882a]1038                                                std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1039                                                assert( params.size() == 2 );
[44f6341]1040                                                arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
[4d4882a]1041                                        }
1042                                        InitExpander srcParam( arg2 );
[44f6341]1043                                        SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
[c8dfcd3]1044
1045                                        assert( stmt.size() <= 1 );
1046                                        if ( stmt.size() == 1 ) {
1047                                                Statement * callStmt = stmt.front();
1048
1049                                                MutatingResolver resolver( *this );
1050                                                try {
1051                                                        callStmt->acceptMutator( resolver );
1052                                                        if ( isCtor ) {
1053                                                                function->get_statements()->push_front( callStmt );
1054                                                        } else {
1055                                                                // destructor statements should be added at the end
1056                                                                function->get_statements()->push_back( callStmt );
1057                                                        }
1058                                                } catch ( SemanticError & error ) {
[64ac636]1059                                                        emit( funcDecl->location, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed",  " and no ", isCtor ? "default constructor" : "destructor", " found" );
[c8dfcd3]1060                                                }
1061                                        }
1062                                }
1063                                leaveScope();
1064                        }
[64ac636]1065                        if (! errors.isEmpty()) {
1066                                throw errors;
1067                        }
[79970ed]1068                }
1069
[c8dfcd3]1070                void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
[79970ed]1071                        if ( ! checkWarnings( function ) ) return;
1072
1073                        std::string fname = getFunctionName( appExpr );
1074                        if ( fname == function->get_name() ) {
1075                                // call to same kind of function
1076                                Expression * firstParam = appExpr->get_args().front();
1077
1078                                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
1079                                        // if calling another constructor on thisParam, assume that function handles
1080                                        // all members - if it doesn't a warning will appear in that function.
1081                                        if ( varExpr->get_var() == thisParam ) {
1082                                                unhandled.clear();
1083                                        }
1084                                } else {
1085                                        // if first parameter is a member expression then
1086                                        // remove the member from unhandled set.
1087                                        handleFirstParam( firstParam );
1088                                }
1089                        }
1090
1091                        Parent::visit( appExpr );
1092                }
1093
[c8dfcd3]1094                void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
[79970ed]1095                        using namespace std;
1096                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
1097                                if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
1098                                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1099                                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1100                                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1101                                                                if ( varExpr->get_var() == thisParam ) {
1102                                                                        unhandled.erase( memberExpr->get_member() );
1103                                                                }
1104                                                        }
1105                                                }
1106                                        }
1107                                }
1108                        }
1109                }
1110
[c8dfcd3]1111                void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
[79970ed]1112                        if ( ! checkWarnings( function ) ) return;
[c8dfcd3]1113                        if ( ! isCtor ) return;
[79970ed]1114
1115                        if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
1116                                if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
1117                                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
1118                                                if ( varExpr->get_var() == thisParam ) {
1119                                                        if ( unhandled.count( memberExpr->get_member() ) ) {
1120                                                                // emit a warning because a member was used before it was constructed
[64ac636]1121                                                                usedUninit.insert( { memberExpr->get_member(), memberExpr->location } );
[79970ed]1122                                                        }
1123                                                }
1124                                        }
1125                                }
1126                        }
1127                        Parent::visit( memberExpr );
1128                }
[3906301]1129
1130                template< typename Visitor, typename... Params >
[64ac636]1131                void error( Visitor & v, CodeLocation loc, const Params &... params ) {
1132                        SemanticError err( toString( params... ) );
1133                        err.set_location( loc );
1134                        v.errors.append( err );
[3906301]1135                }
1136
1137                template< typename... Params >
[64ac636]1138                void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
[3906301]1139                        // toggle warnings vs. errors here.
1140                        // warn( params... );
[64ac636]1141                        error( *this, loc, params... );
[3906301]1142                }
[c8dfcd3]1143
1144                DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
1145                        // add object to the indexer assumes that there will be no name collisions
1146                        // in generated code. If this changes, add mutate methods for entities with
1147                        // scope and call {enter,leave}Scope explicitly.
1148                        objectDecl->accept( indexer );
1149                        return objectDecl;
1150                }
1151
1152                Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
1153                        return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
1154                }
[b6fe7e6]1155
1156                Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
1157                        static UniqueName tempNamer( "_tmp_ctor_expr" );
[f0121d7]1158                        // xxx - is the size check necessary?
[906e24d]1159                        assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
[b7b8674]1160
1161                        // xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary.
[68fe077a]1162                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), Type::StorageClasses(), LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
[b6fe7e6]1163                        addDeclaration( tmp );
1164
[627f585]1165                        // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
[b6fe7e6]1166                        ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1167                        TypeSubstitution * env = ctorExpr->get_env();
1168                        ctorExpr->set_callExpr( nullptr );
1169                        ctorExpr->set_env( nullptr );
1170
1171                        Expression *& firstArg = callExpr->get_args().front();
1172                        UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
1173                        assign->get_args().push_back( new VariableExpr( tmp ) );
1174                        assign->get_args().push_back( firstArg );
[906e24d]1175                        assign->set_result( ctorExpr->get_result()->clone() );
[b6fe7e6]1176                        firstArg = assign;
1177
1178                        CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
1179                        commaExpr->set_env( env );
1180                        delete ctorExpr;
1181                        return commaExpr;
1182                }
[c2931ea]1183        } // namespace
[71f4e4f]1184} // namespace InitTweak
1185
1186// Local Variables: //
1187// tab-width: 4 //
1188// mode: c++ //
1189// compile-command: "make install" //
1190// End: //
Note: See TracBrowser for help on using the repository browser.