source: src/InitTweak/FixInit.cc @ 696bf6e

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 696bf6e was 696bf6e, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Convert FixCtorExprs? to PassVisitor?

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