source: src/InitTweak/FixInit.cc @ 933f32f

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 933f32f was 933f32f, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' into cleanup-dtors

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