source: src/InitTweak/FixInitNew.cpp @ 490fb92e

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 490fb92e was 490fb92e, checked in by Fangren Yu <f37yu@…>, 4 years ago

move FixInit? to new ast

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