source: src/InitTweak/FixInit.cc @ c13e8dc8

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

Merge branch 'master' into cleanup-dtors

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