source: src/InitTweak/FixInit.cpp @ f988834

Last change on this file since f988834 was 5bf685f, checked in by Andrew Beach <ajbeach@…>, 6 months ago

Replayed maybeClone with maybeCopy, removed unused helppers in utility.h and pushed some includes out of headers.

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