source: src/InitTweak/FixInit.cc @ c09e4bc

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

add gcc attributes to ObjectDecl?, hoist destructed static variables, add breaks to end of generated switch

  • Property mode set to 100644
File size: 29.6 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 : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:41:15 2016
13// Update Count     : 34
14//
15
16#include <stack>
17#include <list>
18#include <iterator>
19#include <algorithm>
20#include "InitTweak.h"
21#include "FixInit.h"
22#include "FixGlobalInit.h"
23#include "ResolvExpr/Resolver.h"
24#include "ResolvExpr/typeops.h"
25#include "SynTree/Declaration.h"
26#include "SynTree/Type.h"
27#include "SynTree/Expression.h"
28#include "SynTree/Attribute.h"
29#include "SynTree/Statement.h"
30#include "SynTree/Initializer.h"
31#include "SynTree/Mutator.h"
32#include "SymTab/Indexer.h"
33#include "GenPoly/PolyMutator.h"
34#include "SynTree/AddStmtVisitor.h"
35
36bool ctordtorp = false;
37bool ctorp = false;
38bool cpctorp = false;
39bool dtorp = false;
40#define PRINT( text ) if ( ctordtorp ) { text }
41#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
42#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
43
44namespace InitTweak {
45        namespace {
46                const std::list<Label> noLabels;
47                const std::list<Expression*> noDesignators;
48
49                class InsertImplicitCalls : public GenPoly::PolyMutator {
50                public:
51                        /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
52                        /// function calls need their parameters to be copy constructed
53                        static void insert( std::list< Declaration * > & translationUnit );
54
55                        virtual Expression * mutate( ApplicationExpr * appExpr );
56                };
57
58                class ResolveCopyCtors : public SymTab::Indexer {
59                public:
60                        /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
61                        /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
62                        /// arguments and return value temporaries
63                        static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
64
65                        virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
66
67                        /// create and resolve ctor/dtor expression: fname(var, [cpArg])
68                        ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
69                        /// true if type does not need to be copy constructed to ensure correctness
70                        bool skipCopyConstruct( Type * );
71                private:
72                        TypeSubstitution * env;
73                };
74
75                /// collects constructed object decls - used as a base class
76                class ObjDeclCollector : public AddStmtVisitor {
77                  public:
78                        typedef AddStmtVisitor Parent;
79                        using Parent::visit;
80                        typedef std::set< ObjectDecl * > ObjectSet;
81                        virtual void visit( CompoundStmt *compoundStmt );
82                        virtual void visit( DeclStmt *stmt );
83                  protected:
84                        ObjectSet curVars;
85                };
86
87                // debug
88                struct printSet {
89                        typedef ObjDeclCollector::ObjectSet ObjectSet;
90                        printSet( const ObjectSet & objs ) : objs( objs ) {}
91                        const ObjectSet & objs;
92                };
93                std::ostream & operator<<( std::ostream & out, const printSet & set) {
94                        out << "{ ";
95                        for ( ObjectDecl * obj : set.objs ) {
96                                out << obj->get_name() << ", " ;
97                        } // for
98                        out << " }";
99                        return out;
100                }
101
102                class LabelFinder : public ObjDeclCollector {
103                  public:
104                        typedef ObjDeclCollector Parent;
105                        typedef std::map< Label, ObjectSet > LabelMap;
106                        // map of Label -> live variables at that label
107                        LabelMap vars;
108
109                        void handleStmt( Statement * stmt );
110
111                        // xxx - This needs to be done better.
112                        // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
113                        // expressions, all statements, etc.)  important to have this to provide a single entry point so that as new
114                        // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
115                        // every specialized class knows about every new kind of statement that might be added.
116                        virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
117                        virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
118                        virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
119                        virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
120                        virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
121                        virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
122                        virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123                        virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124                        virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125                        virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126                        virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127                        virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128                        virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129                        virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
130                        virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
131                        virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
132                };
133
134                class InsertDtors : public ObjDeclCollector {
135                public:
136                        /// insert destructor calls at the appropriate places.  must happen before CtorInit nodes are removed
137                        /// (currently by FixInit)
138                        static void insert( std::list< Declaration * > & translationUnit );
139
140                        typedef ObjDeclCollector Parent;
141                        typedef std::list< ObjectDecl * > OrderedDecls;
142                        typedef std::list< OrderedDecls > OrderedDeclsStack;
143
144                        InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
145
146                        virtual void visit( ObjectDecl * objDecl );
147
148                        virtual void visit( CompoundStmt * compoundStmt );
149                        virtual void visit( ReturnStmt * returnStmt );
150                        virtual void visit( BranchStmt * stmt );
151                private:
152                        void handleGoto( BranchStmt * stmt );
153
154                        LabelFinder::LabelMap & labelVars;
155                        OrderedDeclsStack reverseDeclOrder;
156                };
157
158                class FixInit : public GenPoly::PolyMutator {
159                  public:
160                        /// expand each object declaration to use its constructor after it is declared.
161                        static void fixInitializers( std::list< Declaration * > &translationUnit );
162
163                        virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
164
165                        std::list< Declaration * > staticDtorDecls;
166                };
167
168                class FixCopyCtors : public GenPoly::PolyMutator {
169                  public:
170                        /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
171                        /// and destructors
172                        static void fixCopyCtors( std::list< Declaration * > &translationUnit );
173
174                        virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
175                };
176        } // namespace
177
178        void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
179                // fixes ConstructorInit for global variables. should happen before fixInitializers.
180                InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
181
182                InsertImplicitCalls::insert( translationUnit );
183                ResolveCopyCtors::resolveImplicitCalls( translationUnit );
184                InsertDtors::insert( translationUnit );
185                FixInit::fixInitializers( translationUnit );
186
187                // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
188                FixCopyCtors::fixCopyCtors( translationUnit );
189        }
190
191        namespace {
192                void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
193                        InsertImplicitCalls inserter;
194                        mutateAll( translationUnit, inserter );
195                }
196
197                void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
198                        ResolveCopyCtors resolver;
199                        acceptAll( translationUnit, resolver );
200                }
201
202                void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
203                        FixInit fixer;
204
205                        // can't use mutateAll, because need to insert declarations at top-level
206                        // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
207                        SemanticError errors;
208                        for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
209                                try {
210                                        *i = maybeMutate( *i, fixer );
211                                        translationUnit.splice( i, fixer.staticDtorDecls );
212                                } catch( SemanticError &e ) {
213                                        errors.append( e );
214                                } // try
215                        } // for
216                        if ( ! errors.isEmpty() ) {
217                                throw errors;
218                        } // if
219                }
220
221                void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
222                        LabelFinder finder;
223                        InsertDtors inserter( finder );
224                        acceptAll( translationUnit, finder );
225                        acceptAll( translationUnit, inserter );
226                }
227
228                void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
229                        FixCopyCtors fixer;
230                        mutateAll( translationUnit, fixer );
231                }
232
233                Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
234                        appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
235                        assert( appExpr );
236
237                        if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
238                                if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
239                                        // optimization: don't need to copy construct in order to call intrinsic functions
240                                        return appExpr;
241                                } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
242                                        FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
243                                        assert( ftype );
244                                        if ( (funcDecl->get_name() == "?{}" || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
245                                                Type * t1 = ftype->get_parameters().front()->get_type();
246                                                Type * t2 = ftype->get_parameters().back()->get_type();
247                                                PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
248                                                assert( ptrType );
249
250                                                if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
251                                                        // optimization: don't need to copy construct in order to call a copy constructor or
252                                                        // assignment operator
253                                                        return appExpr;
254                                                } // if
255                                        } else if ( funcDecl->get_name() == "^?{}" ) {
256                                                // correctness: never copy construct arguments to a destructor
257                                                return appExpr;
258                                        } // if
259                                } // if
260                        } // if
261                        CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
262
263                        // wrap each function call so that it is easy to identify nodes that have to be copy constructed
264                        ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
265                        // save the type substitution onto the new node so that it is easy to find.
266                        // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
267                        // The substitution is needed to obtain the type of temporary variables so that copy constructor
268                        // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
269                        // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
270                        // saves the environment, or compute the types of temporaries here, but it's much simpler to
271                        // save the environment here, and more cohesive to compute temporary variables and resolve copy
272                        // constructor calls together.
273                        assert( env );
274                        expr->set_env( env );
275                        return expr;
276                }
277
278                bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
279                        return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
280                }
281
282                ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
283                        assert( var );
284                        UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
285                        untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
286                        if (cpArg) untyped->get_args().push_back( cpArg );
287
288                        // resolve copy constructor
289                        // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
290                        // (VariableExpr and already resolved expression)
291                        CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
292                        ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
293                        if ( resolved->get_env() ) {
294                                env->add( *resolved->get_env() );
295                        } // if
296
297                        assert( resolved );
298                        delete untyped;
299                        return resolved;
300                }
301
302                void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
303                        static UniqueName tempNamer("_tmp_cp");
304                        static UniqueName retNamer("_tmp_cp_ret");
305
306                        CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
307                        Visitor::visit( impCpCtorExpr );
308                        env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
309
310                        ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
311
312                        // take each argument and attempt to copy construct it.
313                        for ( Expression * & arg : appExpr->get_args() ) {
314                                CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
315                                // xxx - need to handle tuple arguments
316                                assert( ! arg->get_results().empty() );
317                                Type * result = arg->get_results().front();
318                                if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
319                                // type may involve type variables, so apply type substitution to get temporary variable's actual type
320                                result = result->clone();
321                                impCpCtorExpr->get_env()->apply( result );
322                                ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
323                                tmp->get_type()->set_isConst( false );
324
325                                // create and resolve copy constructor
326                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
327                                ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
328
329                                // if the chosen constructor is intrinsic, the copy is unnecessary, so
330                                // don't create the temporary and don't call the copy constructor
331                                VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
332                                assert( function );
333                                if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
334                                        // replace argument to function call with temporary
335                                        arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
336                                        impCpCtorExpr->get_tempDecls().push_back( tmp );
337                                        impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
338                                } // if
339                        } // for
340
341                        // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
342                        // initialized with the return value and is destructed later
343                        // xxx - handle multiple return values
344                        ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
345                        // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
346                        // level. Trying to pass that environment along.
347                        callExpr->set_env( impCpCtorExpr->get_env()->clone() );
348                        for ( Type * result : appExpr->get_results() ) {
349                                result = result->clone();
350                                impCpCtorExpr->get_env()->apply( result );
351                                ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
352                                ret->get_type()->set_isConst( false );
353                                impCpCtorExpr->get_returnDecls().push_back( ret );
354                                CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
355                                impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
356                        } // for
357                        CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
358                }
359
360
361                Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
362                        CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
363
364                        impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
365                        assert( impCpCtorExpr );
366
367                        std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
368                        std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
369                        std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
370
371                        // add all temporary declarations and their constructors
372                        for ( ObjectDecl * obj : tempDecls ) {
373                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
374                        } // for
375                        for ( ObjectDecl * obj : returnDecls ) {
376                                stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
377                        } // for
378
379                        // add destructors after current statement
380                        for ( Expression * dtor : dtors ) {
381                                stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
382                        } // for
383
384                        // xxx - update to work with multiple return values
385                        ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
386                        Expression * callExpr = impCpCtorExpr->get_callExpr();
387
388                        CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
389
390                        // detach fields from wrapper node so that it can be deleted without deleting too much
391                        dtors.clear();
392                        tempDecls.clear();
393                        returnDecls.clear();
394                        impCpCtorExpr->set_callExpr( NULL );
395                        impCpCtorExpr->set_env( NULL );
396                        delete impCpCtorExpr;
397
398                        if ( returnDecl ) {
399                                UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
400                                assign->get_args().push_back( new VariableExpr( returnDecl ) );
401                                assign->get_args().push_back( callExpr );
402                                // know the result type of the assignment is the type of the LHS (minus the pointer), so
403                                // add that onto the assignment expression so that later steps have the necessary information
404                                assign->add_result( returnDecl->get_type()->clone() );
405
406                                Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
407                                if ( callExpr->get_results().front()->get_isLvalue() ) {
408                                        // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
409                                        // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
410                                        // type of the return temporary from T to T* to properly capture the return value. Then dereference
411                                        // the result of the comma expression, since the lvalue returning call was originally wrapped with
412                                        // an AddressExpr.  Effectively, this turns
413                                        //   lvalue T f();
414                                        //   &*f()
415                                        // into
416                                        //   T * tmp_cp_retN;
417                                        //   tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
418                                        // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
419                                        assign->get_args().back() = new AddressExpr( assign->get_args().back() );
420
421                                        Type * resultType = returnDecl->get_type()->clone();
422                                        returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
423                                        UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
424                                        deref->get_args().push_back( retExpr );
425                                        deref->add_result( resultType );
426                                        retExpr = deref;
427                                } // if
428                                // xxx - might need to set env on retExpr...
429                                // retExpr->set_env( env->clone() );
430                                return retExpr;
431                        } else {
432                                return callExpr;
433                        } // if
434                }
435
436                DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
437                        // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
438                        // is removed from the ObjectDecl
439                        objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
440
441                        if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
442                                // a decision should have been made by the resolver, so ctor and init are not both non-NULL
443                                assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
444                                if ( Statement * ctor = ctorInit->get_ctor() ) {
445                                        if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
446                                                // originally wanted to take advantage of gcc nested functions, but
447                                                // we get memory errors with this approach. To remedy this, the static
448                                                // variable is hoisted when the destructor needs to be called.
449                                                //
450                                                // generate:
451                                                // static T __objName_static_varN;
452                                                // void __objName_dtor_atexitN() {
453                                                //   __dtor__...;
454                                                // }
455                                                // int f(...) {
456                                                //   ...
457                                                //   static bool __objName_uninitialized = true;
458                                                //   if (__objName_uninitialized) {
459                                                //     __ctor(__objName);
460                                                //     __objName_uninitialized = false;
461                                                //     atexit(__objName_dtor_atexitN);
462                                                //   }
463                                                //   ...
464                                                // }
465
466                                                static UniqueName dtorCallerNamer( "_dtor_atexit" );
467
468                                                // static bool __objName_uninitialized = true
469                                                BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
470                                                SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
471                                                ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
472                                                isUninitializedVar->fixUniqueId();
473
474                                                // __objName_uninitialized = false;
475                                                UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
476                                                setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
477                                                setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
478
479                                                // generate body of if
480                                                CompoundStmt * initStmts = new CompoundStmt( noLabels );
481                                                std::list< Statement * > & body = initStmts->get_kids();
482                                                body.push_back( ctor );
483                                                body.push_back( new ExprStmt( noLabels, setTrue ) );
484
485                                                // put it all together
486                                                IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
487                                                stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
488                                                stmtsToAddAfter.push_back( ifStmt );
489
490                                                if ( ctorInit->get_dtor() ) {
491                                                        // if the object has a non-trivial destructor, have to
492                                                        // hoist it and the object into the global space and
493                                                        // call the destructor function with atexit.
494
495                                                        Statement * dtorStmt = ctorInit->get_dtor()->clone();
496
497                                                        // void __objName_dtor_atexitN(...) {...}
498                                                        FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
499                                                        dtorCaller->fixUniqueId();
500                                                        dtorCaller->get_statements()->get_kids().push_back( dtorStmt );
501
502                                                        // atexit(dtor_atexit);
503                                                        UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
504                                                        callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
505
506                                                        body.push_back( new ExprStmt( noLabels, callAtexit ) );
507
508                                                        // hoist variable and dtor caller decls to list of decls that will be added into global scope
509                                                        staticDtorDecls.push_back( objDecl );
510                                                        staticDtorDecls.push_back( dtorCaller );
511
512                                                        // need to rename object uniquely since it now appears
513                                                        // at global scope and there could be multiple function-scoped
514                                                        // static variables with the same name in different functions.
515                                                        static UniqueName staticNamer( "_static_var" );
516                                                        objDecl->set_mangleName( objDecl->get_mangleName() + staticNamer.newName() );
517
518                                                        objDecl->set_init( NULL );
519                                                        ctorInit->set_ctor( NULL );
520                                                        delete ctorInit;
521
522                                                        // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
523                                                        // create a new object which is never used
524                                                        static UniqueName dummyNamer( "_dummy" );
525                                                        ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
526                                                        return dummy;
527                                                }
528                                        } else {
529                                                stmtsToAddAfter.push_back( ctor );
530                                        } // if
531                                        objDecl->set_init( NULL );
532                                        ctorInit->set_ctor( NULL );
533                                } else if ( Initializer * init = ctorInit->get_init() ) {
534                                        objDecl->set_init( init );
535                                        ctorInit->set_init( NULL );
536                                } else {
537                                        // no constructor and no initializer, which is okay
538                                        objDecl->set_init( NULL );
539                                } // if
540                                delete ctorInit;
541                        } // if
542                        return objDecl;
543                }
544
545                void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
546                        std::set< ObjectDecl * > prevVars = curVars;
547                        Parent::visit( compoundStmt );
548                        curVars = prevVars;
549                }
550
551                void ObjDeclCollector::visit( DeclStmt *stmt ) {
552                        // keep track of all variables currently in scope
553                        if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
554                                curVars.insert( objDecl );
555                        } // if
556                        Parent::visit( stmt );
557                }
558
559                void LabelFinder::handleStmt( Statement * stmt ) {
560                        // for each label, remember the variables in scope at that label.
561                        for ( Label l : stmt->get_labels() ) {
562                                vars[l] = curVars;
563                        } // for
564                }
565
566                template<typename Iterator, typename OutputIterator>
567                void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
568                        for ( Iterator it = begin ; it != end ; ++it ) {
569                                // extract destructor statement from the object decl and insert it into the output. Note that this is
570                                // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
571                                // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
572                                // contain side effects.
573                                ObjectDecl * objDecl = *it;
574                                ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
575                                assert( ctorInit && ctorInit->get_dtor() );
576                                *out++ = ctorInit->get_dtor()->clone();
577                        } // for
578                }
579
580                void InsertDtors::visit( ObjectDecl * objDecl ) {
581                        // remember non-static destructed objects so that their destructors can be inserted later
582                        if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
583                                if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
584                                        // a decision should have been made by the resolver, so ctor and init are not both non-NULL
585                                        assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
586                                        Statement * dtor = ctorInit->get_dtor();
587                                        if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
588                                                // don't need to call intrinsic dtor, because it does nothing, but
589                                                // non-intrinsic dtors must be called
590                                                reverseDeclOrder.front().push_front( objDecl );
591                                        } // if
592                                } // if
593                        } // if
594                        Parent::visit( objDecl );
595                }
596
597                void InsertDtors::visit( CompoundStmt * compoundStmt ) {
598                        // visit statements - this will also populate reverseDeclOrder list.  don't want to dump all destructors
599                        // when block is left, just the destructors associated with variables defined in this block, so push a new
600                        // list to the top of the stack so that we can differentiate scopes
601                        reverseDeclOrder.push_front( OrderedDecls() );
602                        Parent::visit( compoundStmt );
603
604                        // add destructors for the current scope that we're exiting
605                        std::list< Statement * > & statements = compoundStmt->get_kids();
606                        insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
607                        reverseDeclOrder.pop_front();
608                }
609
610                void InsertDtors::visit( ReturnStmt * returnStmt ) {
611                        // return exits all scopes, so dump destructors for all scopes
612                        for ( OrderedDecls & od : reverseDeclOrder ) {
613                                insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
614                        } // for
615                }
616
617                // Handle break/continue/goto in the same manner as C++.  Basic idea: any objects that are in scope at the
618                // BranchStmt but not at the labelled (target) statement must be destructed.  If there are any objects in scope
619                // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
620                // of the error.  See C++ Reference 6.6 Jump Statements for details.
621                void InsertDtors::handleGoto( BranchStmt * stmt ) {
622                        assert( stmt->get_target() != "" && "BranchStmt missing a label" );
623                        // S_L = lvars = set of objects in scope at label definition
624                        // S_G = curVars = set of objects in scope at goto statement
625                        ObjectSet & lvars = labelVars[ stmt->get_target() ];
626
627                        DTOR_PRINT(
628                                std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
629                                std::cerr << "S_G = " << printSet( curVars ) << std::endl;
630                                std::cerr << "S_L = " << printSet( lvars ) << std::endl;
631                        )
632
633                        ObjectSet diff;
634                        // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
635                        std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
636                        DTOR_PRINT(
637                                std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
638                        )
639                        if ( ! diff.empty() ) {
640                                throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
641                        } // if
642                        // S_G-S_L results in set of objects that must be destructed
643                        diff.clear();
644                        std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
645                        DTOR_PRINT(
646                                std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
647                        )
648                        if ( ! diff.empty() ) {
649                                // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
650                                OrderedDecls ordered;
651                                for ( OrderedDecls & rdo : reverseDeclOrder ) {
652                                        // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
653                                        copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
654                                } // for
655                                insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
656                        } // if
657                }
658
659                void InsertDtors::visit( BranchStmt * stmt ) {
660                        switch( stmt->get_type() ) {
661                          case BranchStmt::Continue:
662                          case BranchStmt::Break:
663                                // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
664                                // always be empty), but it serves as a small sanity check.
665                          case BranchStmt::Goto:
666                                handleGoto( stmt );
667                                break;
668                          default:
669                                assert( false );
670                        } // switch
671                }
672        } // namespace
673} // namespace InitTweak
674
675// Local Variables: //
676// tab-width: 4 //
677// mode: c++ //
678// compile-command: "make install" //
679// End: //
Note: See TracBrowser for help on using the repository browser.