source: src/InitTweak/FixInit.cc @ 540de412

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 540de412 was 540de412, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

'merge' type substitutions from resolved copy constructors, add case to getBaseVar for CommaExpr?

  • Property mode set to 100644
File size: 19.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// FixInit.h --
8//
9// Author           : Rob Schluntz
10// Created On       : Wed Jan 13 16:29:30 2016
11// Last Modified By : Rob Schluntz
12// Last Modified On : Mon May 02 14:57:45 2016
13// Update Count     : 30
14//
15
16#include <stack>
17#include <list>
18#include "FixInit.h"
19#include "ResolvExpr/Resolver.h"
20#include "ResolvExpr/typeops.h"
21#include "SynTree/Declaration.h"
22#include "SynTree/Type.h"
23#include "SynTree/Expression.h"
24#include "SynTree/Statement.h"
25#include "SynTree/Initializer.h"
26#include "SynTree/Mutator.h"
27#include "SymTab/Indexer.h"
28#include "GenPoly/PolyMutator.h"
29#include "GenPoly/GenPoly.h"
30
31bool ctordtorp = false;
32#define PRINT( text ) if ( ctordtorp ) { text }
33
34namespace InitTweak {
35        namespace {
36                const std::list<Label> noLabels;
37                const std::list<Expression*> noDesignators;
38        }
39
40        class InsertImplicitCalls : public GenPoly::PolyMutator {
41        public:
42                /// wrap function application expressions as ImplicitCopyCtorExpr nodes
43                /// so that it is easy to identify which function calls need their parameters
44                /// to be copy constructed
45                static void insert( std::list< Declaration * > & translationUnit );
46
47                virtual Expression * mutate( ApplicationExpr * appExpr );
48        };
49
50        class ResolveCopyCtors : public SymTab::Indexer {
51        public:
52                /// generate temporary ObjectDecls for each argument and return value of each
53                /// ImplicitCopyCtorExpr, generate/resolve copy construction expressions for each,
54                /// and generate/resolve destructors for both arguments and return value temporaries
55                static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
56
57                virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
58
59                /// create and resolve ctor/dtor expression: fname(var, [cpArg])
60                ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
61                /// true if type does not need to be copy constructed to ensure correctness
62                bool skipCopyConstruct( Type * );
63        private:
64                TypeSubstitution * env;
65        };
66
67        class FixInit : public GenPoly::PolyMutator {
68          public:
69                /// expand each object declaration to use its constructor after it is declared.
70                /// insert destructor calls at the appropriate places
71                static void fixInitializers( std::list< Declaration * > &translationUnit );
72
73                virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
74
75                virtual CompoundStmt * mutate( CompoundStmt * compoundStmt );
76                virtual Statement * mutate( ReturnStmt * returnStmt );
77                virtual Statement * mutate( BranchStmt * branchStmt );
78
79          private:
80                // stack of list of statements - used to differentiate scopes
81                std::list< std::list< Statement * > > dtorStmts;
82        };
83
84        class FixCopyCtors : public GenPoly::PolyMutator {
85          public:
86                /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors,
87                /// call expression, and destructors
88                static void fixCopyCtors( std::list< Declaration * > &translationUnit );
89
90                virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
91
92          private:
93                // stack of list of statements - used to differentiate scopes
94                std::list< std::list< Statement * > > dtorStmts;
95        };
96
97        void fix( std::list< Declaration * > & translationUnit ) {
98                InsertImplicitCalls::insert( translationUnit );
99                ResolveCopyCtors::resolveImplicitCalls( translationUnit );
100                FixInit::fixInitializers( translationUnit );
101                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
102                FixCopyCtors::fixCopyCtors( translationUnit );
103        }
104
105        void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
106                InsertImplicitCalls inserter;
107                mutateAll( translationUnit, inserter );
108        }
109
110        void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
111                ResolveCopyCtors resolver;
112                acceptAll( translationUnit, resolver );
113        }
114
115        void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
116                FixInit fixer;
117                mutateAll( translationUnit, fixer );
118        }
119
120        void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
121                FixCopyCtors fixer;
122                mutateAll( translationUnit, fixer );
123        }
124
125        Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
126                appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
127                assert( appExpr );
128
129                if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
130                        if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
131                                // optimization: don't need to copy construct in order to call intrinsic functions
132                                return appExpr;
133                        } else if ( FunctionDecl * funcDecl = dynamic_cast< FunctionDecl * > ( function->get_var() ) ) {
134                                FunctionType * ftype = funcDecl->get_functionType();
135                                if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
136                                        Type * t1 = ftype->get_parameters().front()->get_type();
137                                        Type * t2 = ftype->get_parameters().back()->get_type();
138                                        PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
139                                        assert( ptrType );
140                                        if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
141                                                // optimization: don't need to copy construct in order to call a copy constructor or
142                                                // assignment operator
143                                                return appExpr;
144                                        }
145                                } else if ( funcDecl->get_name() == "^?{}" ) {
146                                        // correctness: never copy construct arguments to a destructor
147                                        return appExpr;
148                                }
149                        }
150                }
151                PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
152
153                // wrap each function call so that it is easy to identify nodes that have to be copy constructed
154                ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
155                // save the type substitution onto the new node so that it is easy to find.
156                // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
157                // The substitution is needed to obtain the type of temporary variables so that copy constructor
158                // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
159                // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
160                // saves the environment, or compute the types of temporaries here, but it's much simpler to
161                // save the environment here, and more cohesive to compute temporary variables and resolve copy
162                // constructor calls together.
163                assert( env );
164                expr->set_env( env );
165                return expr;
166        }
167
168        bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
169                return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
170        }
171
172        ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
173                assert( var );
174                UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
175                untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
176                if (cpArg) untyped->get_args().push_back( cpArg );
177
178                // resolve copy constructor
179                // should only be one alternative for copy ctor and dtor expressions, since
180                // all arguments are fixed (VariableExpr and already resolved expression)
181                PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
182                ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
183                if ( resolved->get_env() ) {
184                        env->add( *resolved->get_env() );
185                }
186
187                assert( resolved );
188                delete untyped;
189                return resolved;
190        }
191
192        void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
193                static UniqueName tempNamer("_tmp_cp");
194                static UniqueName retNamer("_tmp_cp_ret");
195
196                PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
197                Visitor::visit( impCpCtorExpr );
198                env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
199
200                ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
201
202                // take each argument and attempt to copy construct it.
203                for ( Expression * & arg : appExpr->get_args() ) {
204                        PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
205                        // xxx - need to handle tuple arguments
206                        assert( ! arg->get_results().empty() );
207                        Type * result = arg->get_results().front();
208                        if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
209                        // type may involve type variables, so apply type substitution to get temporary variable's actual type
210                        result = result->clone();
211                        impCpCtorExpr->get_env()->apply( result );
212                        ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
213                        tmp->get_type()->set_isConst( false );
214
215                        // create and resolve copy constructor
216                        PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
217                        ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
218
219                        // if the chosen constructor is intrinsic, the copy is unnecessary, so
220                        // don't create the temporary and don't call the copy constructor
221                        VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
222                        assert( function );
223                        if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
224                                // replace argument to function call with temporary
225                                arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
226                                impCpCtorExpr->get_tempDecls().push_back( tmp );
227                                impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
228                        }
229                }
230
231                // each return value from the call needs to be connected with an ObjectDecl
232                // at the call site, which is initialized with the return value and is destructed
233                // later
234                // xxx - handle multiple return values
235                ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
236                // xxx - is this right? callExpr may not have the right environment, because it was attached
237                // at a higher level. Trying to pass that environment along.
238                callExpr->set_env( impCpCtorExpr->get_env()->clone() );
239                for ( Type * result : appExpr->get_results() ) {
240                        result = result->clone();
241                        impCpCtorExpr->get_env()->apply( result );
242                        ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
243                        ret->get_type()->set_isConst( false );
244                        impCpCtorExpr->get_returnDecls().push_back( ret );
245                        PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
246                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
247                }
248                PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
249        }
250
251
252        Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
253                PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
254
255                impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
256                assert( impCpCtorExpr );
257
258                std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
259                std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
260                std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
261
262                // add all temporary declarations and their constructors
263                for ( ObjectDecl * obj : tempDecls ) {
264                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
265                }
266                for ( ObjectDecl * obj : returnDecls ) {
267                        stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
268                }
269
270                // add destructors after current statement
271                for ( Expression * dtor : dtors ) {
272                        stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
273                }
274
275                // xxx - update to work with multiple return values
276                ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
277                Expression * callExpr = impCpCtorExpr->get_callExpr();
278
279                PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
280
281                // xxx - some of these aren't necessary, and can be removed once this is stable
282                dtors.clear();
283                tempDecls.clear();
284                returnDecls.clear();
285                impCpCtorExpr->set_callExpr( NULL );
286                impCpCtorExpr->set_env( NULL );
287                delete impCpCtorExpr;
288
289                if ( returnDecl ) {
290                        UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
291                        assign->get_args().push_back( new VariableExpr( returnDecl ) );
292                        assign->get_args().push_back( callExpr );
293                        // know the result type of the assignment is the type of the LHS (minus the pointer), so
294                        // add that onto the assignment expression so that later steps have the necessary information
295                        assign->add_result( returnDecl->get_type()->clone() );
296
297                        Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
298                        if ( callExpr->get_results().front()->get_isLvalue() ) {
299                                // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any
300                                // lvalue returning non-intrinsic function. Add an AddressExpr to the call to negate
301                                // the derefence and change the type of the return temporary from T to T* to properly
302                                // capture the return value. Then dereference the result of the comma expression, since
303                                // the lvalue returning call was originally wrapped with an AddressExpr.
304                                // Effectively, this turns
305                                //   lvalue T f();
306                                //   &*f()
307                                // into
308                                //   T * tmp_cp_retN;
309                                //   tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
310                                // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
311                                assign->get_args().back() = new AddressExpr( assign->get_args().back() );
312
313                                Type * resultType = returnDecl->get_type()->clone();
314                                returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
315                                UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
316                                deref->get_args().push_back( retExpr );
317                                deref->add_result( resultType );
318                                retExpr = deref;
319                        }
320                        // xxx - might need to set env on retExpr...
321                        // retExpr->set_env( env->clone() );
322                        return retExpr;
323                } else {
324                        return callExpr;
325                }
326        }
327
328        DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
329                // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors
330                // when the init is removed from the ObjectDecl
331                objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
332
333                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
334                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
335                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
336                        if ( Statement * ctor = ctorInit->get_ctor() ) {
337                                if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
338                                        // generate:
339                                        // static bool __objName_uninitialized = true;
340                                        // if (__objName_uninitialized) {
341                                        //   __ctor(__objName);
342                                        //   void dtor_atexit() {
343                                        //     __dtor(__objName);
344                                        //   }
345                                        //   on_exit(dtorOnExit, &__objName);
346                                        //   __objName_uninitialized = false;
347                                        // }
348
349                                        // generate first line
350                                        BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
351                                        SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
352                                        ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
353                                        isUninitializedVar->fixUniqueId();
354
355                                        // void dtor_atexit(...) {...}
356                                        FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + "_dtor_atexit", DeclarationNode::NoStorageClass, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
357                                        dtorCaller->fixUniqueId();
358                                        dtorCaller->get_statements()->get_kids().push_back( ctorInit->get_dtor() );
359
360                                        // on_exit(dtor_atexit);
361                                        UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
362                                        callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
363
364                                        // __objName_uninitialized = false;
365                                        UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
366                                        setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
367                                        setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
368
369                                        // generate body of if
370                                        CompoundStmt * initStmts = new CompoundStmt( noLabels );
371                                        std::list< Statement * > & body = initStmts->get_kids();
372                                        body.push_back( ctor );
373                                        body.push_back( new DeclStmt( noLabels, dtorCaller ) );
374                                        body.push_back( new ExprStmt( noLabels, callAtexit ) );
375                                        body.push_back( new ExprStmt( noLabels, setTrue ) );
376
377                                        // put it all together
378                                        IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
379                                        stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
380                                        stmtsToAddAfter.push_back( ifStmt );
381                                } else {
382                                        stmtsToAddAfter.push_back( ctor );
383                                        dtorStmts.back().push_front( ctorInit->get_dtor() );
384                                }
385                                objDecl->set_init( NULL );
386                                ctorInit->set_ctor( NULL );
387                                ctorInit->set_dtor( NULL );  // xxx - only destruct when constructing? Probably not?
388                        } else if ( Initializer * init = ctorInit->get_init() ) {
389                                objDecl->set_init( init );
390                                ctorInit->set_init( NULL );
391                        } else {
392                                // no constructor and no initializer, which is okay
393                                objDecl->set_init( NULL );
394                        }
395                        delete ctorInit;
396                }
397                return objDecl;
398        }
399
400        template<typename Iterator, typename OutputIterator>
401        void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
402                for ( Iterator it = begin ; it != end ; ++it ) {
403                        // remove if instrinsic destructor statement
404                        // xxx - test user manually calling intrinsic functions - what happens?
405                        if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( *it ) ) {
406                                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
407                                assert( appExpr );
408                                VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
409                                assert( function );
410                                // check for Intrinsic only - don't want to remove all overridable dtors because autogenerated dtor
411                                // will call all member dtors, and some members may have a user defined dtor.
412                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
413                                        // don't need to call intrinsic dtor, because it does nothing
414                                } else {
415                                        // non-intrinsic dtors must be called
416                                        *out++ = (*it)->clone();
417                                }
418                        } else {
419                                // could also be a compound statement with a loop, in the case of an array
420                                *out++ = (*it)->clone();
421                        }
422                }
423        }
424
425
426        CompoundStmt * FixInit::mutate( CompoundStmt * compoundStmt ) {
427                // mutate statements - this will also populate dtorStmts list.
428                // don't want to dump all destructors when block is left,
429                // just the destructors associated with variables defined in this block,
430                // so push a new list to the top of the stack so that we can differentiate scopes
431                dtorStmts.push_back( std::list<Statement *>() );
432
433                compoundStmt = PolyMutator::mutate( compoundStmt );
434                std::list< Statement * > & statements = compoundStmt->get_kids();
435
436                insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( statements ) );
437
438                deleteAll( dtorStmts.back() );
439                dtorStmts.pop_back();
440                return compoundStmt;
441        }
442
443        Statement * FixInit::mutate( ReturnStmt * returnStmt ) {
444                for ( std::list< std::list< Statement * > >::reverse_iterator list = dtorStmts.rbegin(); list != dtorStmts.rend(); ++list ) {
445                        insertDtors( list->begin(), list->end(), back_inserter( stmtsToAdd ) );
446                }
447                return Mutator::mutate( returnStmt );
448        }
449
450        Statement * FixInit::mutate( BranchStmt * branchStmt ) {
451                // TODO: adding to the end of a block isn't sufficient, since
452                // return/break/goto should trigger destructor when block is left.
453                switch( branchStmt->get_type() ) {
454                        case BranchStmt::Continue:
455                        case BranchStmt::Break:
456                                insertDtors( dtorStmts.back().begin(), dtorStmts.back().end(), back_inserter( stmtsToAdd ) );
457                                break;
458                        case BranchStmt::Goto:
459                                // xxx
460                                // if goto leaves a block, generate dtors for every block it leaves
461                                // if goto is in same block but earlier statement, destruct every object that was defined after the statement
462                                break;
463                        default:
464                                assert( false );
465                }
466                return Mutator::mutate( branchStmt );
467        }
468
469
470} // namespace InitTweak
471
472// Local Variables: //
473// tab-width: 4 //
474// mode: c++ //
475// compile-command: "make install" //
476// End: //
Note: See TracBrowser for help on using the repository browser.