source: src/InitTweak/FixInit.cc @ ac74057

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

Convert AutogenTupleRoutines? to PassVisitor?

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