source: src/InitTweak/FixInitNew.cpp @ 09867ec

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 09867ec was 4a8f150, checked in by Andrew Beach <ajbeach@…>, 3 years ago

A quick-fix to get the self-assignment bug working and some clean-up I did on the way.

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