source: src/InitTweak/InitTweak.cc @ b16898e

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

implement implicit ctor/dtor deletion, track managed types when inserting ConstructorInit? nodes, remove fallbackInit case, update tests

  • Property mode set to 100644
File size: 16.5 KB
RevLine 
[4d2434a]1#include <algorithm>
[2b46a13]2#include "InitTweak.h"
3#include "SynTree/Visitor.h"
4#include "SynTree/Statement.h"
5#include "SynTree/Initializer.h"
6#include "SynTree/Expression.h"
[f9cebb5]7#include "SynTree/Attribute.h"
[2b46a13]8#include "GenPoly/GenPoly.h"
[4d4882a]9#include "ResolvExpr/typeops.h"
[2b46a13]10
11namespace InitTweak {
[64071c2]12        namespace {
13                class HasDesignations : public Visitor {
14                public:
15                        bool hasDesignations = false;
16                        template<typename Init>
17                        void handleInit( Init * init ) {
18                                if ( ! init->get_designators().empty() ) hasDesignations = true;
19                                else Visitor::visit( init );
20                        }
21                        virtual void visit( SingleInit * singleInit ) { handleInit( singleInit); }
22                        virtual void visit( ListInit * listInit ) { handleInit( listInit); }
23                };
[2b46a13]24
[4d2434a]25                class InitFlattener : public Visitor {
[64071c2]26                        public:
27                        virtual void visit( SingleInit * singleInit );
28                        virtual void visit( ListInit * listInit );
29                        std::list< Expression * > argList;
30                };
[2b46a13]31
[4d2434a]32                void InitFlattener::visit( SingleInit * singleInit ) {
[64071c2]33                        argList.push_back( singleInit->get_value()->clone() );
34                }
[2b46a13]35
[4d2434a]36                void InitFlattener::visit( ListInit * listInit ) {
37                        // flatten nested list inits
38                        std::list<Initializer*>::iterator it = listInit->begin();
39                        for ( ; it != listInit->end(); ++it ) {
[64071c2]40                                (*it)->accept( *this );
41                        }
42                }
43        }
[2b46a13]44
[64071c2]45        std::list< Expression * > makeInitList( Initializer * init ) {
[4d2434a]46                InitFlattener flattener;
47                maybeAccept( init, flattener );
48                return flattener.argList;
[64071c2]49        }
[2b46a13]50
[64071c2]51        bool isDesignated( Initializer * init ) {
52                HasDesignations finder;
53                maybeAccept( init, finder );
54                return finder.hasDesignations;
55        }
[2b46a13]56
[39f84a4]57        class InitExpander::ExpanderImpl {
58        public:
59                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
[4d2434a]60                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
[39f84a4]61        };
62
63        class InitImpl : public InitExpander::ExpanderImpl {
64        public:
[4d2434a]65                InitImpl( Initializer * init ) : init( init ) {}
[39f84a4]66
67                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
68                        // this is wrong, but just a placeholder for now
[4d2434a]69                        // if ( ! flattened ) flatten( indices );
70                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
71                        return makeInitList( init );
[39f84a4]72                }
[4d2434a]73
74                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]75        private:
[4d2434a]76                Initializer * init;
[39f84a4]77        };
78
79        class ExprImpl : public InitExpander::ExpanderImpl {
80        public:
81                ExprImpl( Expression * expr ) : arg( expr ) {}
82
[9b4c936]83                ~ExprImpl() { delete arg; }
84
[39f84a4]85                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
86                        std::list< Expression * > ret;
87                        Expression * expr = maybeClone( arg );
88                        if ( expr ) {
89                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
90                                        // go through indices and layer on subscript exprs ?[?]
91                                        ++it;
92                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
93                                        subscriptExpr->get_args().push_back( expr );
94                                        subscriptExpr->get_args().push_back( (*it)->clone() );
95                                        expr = subscriptExpr;
96                                }
97                                ret.push_back( expr );
98                        }
99                        return ret;
100                }
[4d2434a]101
102                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]103        private:
104                Expression * arg;
105        };
106
107        InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
108
109        InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
110
111        std::list< Expression * > InitExpander::operator*() {
112                return cur;
113        }
114
115        InitExpander & InitExpander::operator++() {
116                cur = expander->next( indices );
117                return *this;
118        }
119
120        // use array indices list to build switch statement
121        void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
122                indices.push_back( index );
123                indices.push_back( dimension );
124        }
125
[4d2434a]126        void InitExpander::clearArrayIndices() {
[9b4c936]127                deleteAll( indices );
[4d2434a]128                indices.clear();
129        }
130
131        namespace {
[f9cebb5]132                /// given index i, dimension d, initializer init, and callExpr f, generates
133                ///   if (i < d) f(..., init)
134                ///   ++i;
135                /// so that only elements within the range of the array are constructed
[4d2434a]136                template< typename OutIterator >
[f9cebb5]137                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
[4d2434a]138                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
139                        cond->get_args().push_back( index->clone() );
140                        cond->get_args().push_back( dimension->clone() );
141
142                        std::list< Expression * > args = makeInitList( init );
143                        callExpr->get_args().splice( callExpr->get_args().end(), args );
144
145                        *out++ = new IfStmt( noLabels, cond, new ExprStmt( noLabels, callExpr ), NULL );
146
147                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
148                        increment->get_args().push_back( new AddressExpr( index->clone() ) );
149                        *out++ = new ExprStmt( noLabels, increment );
150                }
151
152                template< typename OutIterator >
153                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
154                        if ( idx == idxEnd ) return;
155                        Expression * index = *idx++;
156                        assert( idx != idxEnd );
157                        Expression * dimension = *idx++;
158
[f9cebb5]159                        // xxx - may want to eventually issue a warning here if we can detect
160                        // that the number of elements exceeds to dimension of the array
[4d2434a]161                        if ( idx == idxEnd ) {
162                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
163                                        for ( Initializer * init : *listInit ) {
[f9cebb5]164                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]165                                        }
166                                } else {
[f9cebb5]167                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]168                                }
169                        } else {
170                                std::list< Statement * > branches;
171
172                                unsigned long cond = 0;
173                                ListInit * listInit = dynamic_cast< ListInit * >( init );
174                                if ( ! listInit ) {
175                                        // xxx - this shouldn't be an error, but need a way to
176                                        // terminate without creating output, so should catch this error
177                                        throw SemanticError( "unbalanced list initializers" );
178                                }
[f9cebb5]179
180                                static UniqueName targetLabel( "L__autogen__" );
181                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
[4d2434a]182                                for ( Initializer * init : *listInit ) {
183                                        Expression * condition;
184                                        // check for designations
185                                        // if ( init-> ) {
186                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
187                                                ++cond;
188                                        // } else {
189                                        //      condition = // ... take designation
190                                        //      cond = // ... take designation+1
191                                        // }
192                                        std::list< Statement * > stmts;
193                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
[f9cebb5]194                                        stmts.push_back( new BranchStmt( noLabels, switchLabel, BranchStmt::Break ) );
[4d2434a]195                                        CaseStmt * caseStmt = new CaseStmt( noLabels, condition, stmts );
196                                        branches.push_back( caseStmt );
197                                }
198                                *out++ = new SwitchStmt( noLabels, index->clone(), branches );
[f9cebb5]199                                *out++ = new NullStmt( std::list<Label>{ switchLabel } );
[4d2434a]200                        }
201                }
202        }
203
204        // if array came with an initializer list: initialize each element
205        // may have more initializers than elements in the array - need to check at each index that
206        // we haven't exceeded size.
207        // may have fewer initializers than elements in the array - need to default construct
208        // remaining elements.
209        // To accomplish this, generate switch statement, consuming all of expander's elements
210        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
211                if ( ! init ) return NULL;
[f9cebb5]212                CompoundStmt * block = new CompoundStmt( noLabels );
213                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
214                if ( block->get_kids().empty() ) {
215                        delete block;
[4d2434a]216                        return NULL;
217                } else {
218                        init = NULL; // init was consumed in creating the list init
[f9cebb5]219                        return block;
[4d2434a]220                }
[39f84a4]221        }
222
[4d2434a]223        Statement * ExprImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
224                return NULL;
225        }
226
227        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
228                return expander->buildListInit( dst, indices );
229        }
230
[64071c2]231        bool tryConstruct( ObjectDecl * objDecl ) {
232                return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
233                        (objDecl->get_init() == NULL ||
[1ba88a0]234                                ( objDecl->get_init() != NULL && objDecl->get_init()->get_maybeConstructed() ))
[6cf27a07]235                        && objDecl->get_storageClass() != DeclarationNode::Extern;
[64071c2]236        }
[2b46a13]237
[4d2434a]238        class CallFinder : public Visitor {
239        public:
240                typedef Visitor Parent;
241                CallFinder( const std::list< std::string > & names ) : names( names ) {}
242
243                virtual void visit( ApplicationExpr * appExpr ) {
244                        handleCallExpr( appExpr );
245                }
246
247                virtual void visit( UntypedExpr * untypedExpr ) {
248                        handleCallExpr( untypedExpr );
249                }
250
251                std::list< Expression * > * matches;
252        private:
253                const std::list< std::string > names;
254
255                template< typename CallExpr >
256                void handleCallExpr( CallExpr * expr ) {
257                        Parent::visit( expr );
258                        std::string fname = getFunctionName( expr );
259                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
260                                matches->push_back( expr );
[cad355a]261                        }
[64071c2]262                }
[4d2434a]263        };
264
265        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
266                static CallFinder finder( std::list< std::string >{ "?{}", "^?{}" } );
267                finder.matches = &matches;
268                maybeAccept( stmt, finder );
[64071c2]269        }
[4d2434a]270
271        Expression * getCtorDtorCall( Statement * stmt ) {
272                std::list< Expression * > matches;
273                collectCtorDtorCalls( stmt, matches );
274                assert( matches.size() <= 1 );
275                return matches.size() == 1 ? matches.front() : NULL;
276        }
277
[aedfd91]278        namespace {
279                VariableExpr * getCalledFunction( ApplicationExpr * appExpr ) {
280                        assert( appExpr );
[4d2434a]281                        // xxx - it's possible this can be other things, e.g. MemberExpr, so this is insufficient
[aedfd91]282                        return dynamic_cast< VariableExpr * >( appExpr->get_function() );
283                }
284        }
[70f89d00]285
[aedfd91]286        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
287                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
288                if ( ! appExpr ) return NULL;
289                VariableExpr * function = getCalledFunction( appExpr );
[64071c2]290                assert( function );
291                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
292                // will call all member dtors, and some members may have a user defined dtor.
[aedfd91]293                return function->get_var()->get_linkage() == LinkageSpec::Intrinsic ? appExpr : NULL;
294        }
295
[a465caf]296        namespace {
297                template <typename Predicate>
298                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
299                        std::list< Expression * > callExprs;
300                        collectCtorDtorCalls( stmt, callExprs );
301                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
302                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
303                }
304        }
305
[f9cebb5]306        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
[a465caf]307                return allofCtorDtor( stmt, []( Expression * callExpr ){
[4d2434a]308                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
309                                assert( ! appExpr->get_function()->get_results().empty() );
310                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_results().front() );
311                                assert( funcType );
312                                return funcType->get_parameters().size() == 1;
313                        }
314                        return false;
315                });
[64071c2]316        }
[f1b1e4c]317
[a465caf]318        bool isIntrinsicCallStmt( Statement * stmt ) {
319                return allofCtorDtor( stmt, []( Expression * callExpr ) {
320                        return isIntrinsicCallExpr( callExpr );
321                });
322        }
323
[64071c2]324        namespace {
325                template<typename CallExpr>
326                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
327                        if ( pos >= callExpr->get_args().size() ) assert( false && "asking for argument that doesn't exist. Return NULL/throw exception?" );
328                        for ( Expression *& arg : callExpr->get_args() ) {
329                                if ( pos == 0 ) return arg;
330                                pos--;
331                        }
332                        assert( false );
333                }
334        }
[f1b1e4c]335
[64071c2]336        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
337                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
338                        return callArg( appExpr, pos );
339                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
340                        return callArg( untypedExpr, pos );
341                } else {
342                        assert( false && "Unexpected expression type passed to getCallArg" );
343                }
344        }
[f1b1e4c]345
[64071c2]346        namespace {
[c738ca4]347                std::string funcName( Expression * func ) {
[64071c2]348                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
349                                return nameExpr->get_name();
350                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
351                                return varExpr->get_var()->get_name();
[c738ca4]352                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
353                                return funcName( castExpr->get_arg() );
[64071c2]354                        } else {
355                                assert( false && "Unexpected expression type being called as a function in call expression" );
356                        }
357                }
358        }
[70f89d00]359
[64071c2]360        std::string getFunctionName( Expression * expr ) {
361                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
[c738ca4]362                        return funcName( appExpr->get_function() );
[64071c2]363                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
[c738ca4]364                        return funcName( untypedExpr->get_function() );
[64071c2]365                } else {
[c738ca4]366                        std::cerr << expr << std::endl;
[64071c2]367                        assert( false && "Unexpected expression type passed to getFunctionName" );
368                }
369        }
[10a7775]370
[64071c2]371        Type * getPointerBase( Type * type ) {
372                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
373                        return ptrType->get_base();
374                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
375                        return arrayType->get_base();
376                } else {
377                        return NULL;
378                }
379        }
[10a7775]380
[64071c2]381        Type * isPointerType( Type * type ) {
382                if ( getPointerBase( type ) ) return type;
383                else return NULL;
384        }
[40e636a]385
386        class ConstExprChecker : public Visitor {
387        public:
388                ConstExprChecker() : isConstExpr( true ) {}
389
390                virtual void visit( ApplicationExpr *applicationExpr ) { isConstExpr = false; }
391                virtual void visit( UntypedExpr *untypedExpr ) { isConstExpr = false; }
[1ba88a0]392                virtual void visit( NameExpr *nameExpr ) {
393                        // xxx - temporary hack, because 0 and 1 really should be constexprs, even though they technically aren't in Cforall today
394                        if ( nameExpr->get_name() != "0" && nameExpr->get_name() != "1" ) isConstExpr = false;
395                }
396                // virtual void visit( CastExpr *castExpr ) { isConstExpr = false; }
397                virtual void visit( AddressExpr *addressExpr ) {
398                        // address of a variable or member expression is constexpr
399                        Expression * arg = addressExpr->get_arg();
400                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
401                }
[40e636a]402                virtual void visit( LabelAddressExpr *labAddressExpr ) { isConstExpr = false; }
403                virtual void visit( UntypedMemberExpr *memberExpr ) { isConstExpr = false; }
404                virtual void visit( MemberExpr *memberExpr ) { isConstExpr = false; }
405                virtual void visit( VariableExpr *variableExpr ) { isConstExpr = false; }
406                // these might be okay?
407                // virtual void visit( SizeofExpr *sizeofExpr );
408                // virtual void visit( AlignofExpr *alignofExpr );
409                // virtual void visit( UntypedOffsetofExpr *offsetofExpr );
410                // virtual void visit( OffsetofExpr *offsetofExpr );
411                // virtual void visit( OffsetPackExpr *offsetPackExpr );
412                // virtual void visit( AttrExpr *attrExpr );
413                // virtual void visit( CommaExpr *commaExpr );
414                // virtual void visit( LogicalExpr *logicalExpr );
415                // virtual void visit( ConditionalExpr *conditionalExpr );
416                virtual void visit( TupleExpr *tupleExpr ) { isConstExpr = false; }
417                virtual void visit( SolvedTupleExpr *tupleExpr ) { isConstExpr = false; }
418                virtual void visit( TypeExpr *typeExpr ) { isConstExpr = false; }
419                virtual void visit( AsmExpr *asmExpr ) { isConstExpr = false; }
420                virtual void visit( UntypedValofExpr *valofExpr ) { isConstExpr = false; }
421                virtual void visit( CompoundLiteralExpr *compLitExpr ) { isConstExpr = false; }
422
423                bool isConstExpr;
424        };
425
426        bool isConstExpr( Expression * expr ) {
427                if ( expr ) {
428                        ConstExprChecker checker;
429                        expr->accept( checker );
430                        return checker.isConstExpr;
431                }
432                return true;
433        }
434
435        bool isConstExpr( Initializer * init ) {
436                if ( init ) {
437                        ConstExprChecker checker;
438                        init->accept( checker );
439                        return checker.isConstExpr;
440                } // if
441                // for all intents and purposes, no initializer means const expr
442                return true;
443        }
444
[79970ed]445        bool isConstructor( const std::string & str ) { return str == "?{}"; }
446        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
447        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
[4d4882a]448
449        FunctionDecl * isCopyConstructor( Declaration * decl ) {
450                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
451                if ( ! function ) return 0;
452                if ( ! isConstructor( function->get_name() ) ) return 0;
453                FunctionType * ftype = function->get_functionType();
454                if ( ftype->get_parameters().size() != 2 ) return 0;
455
456                Type * t1 = ftype->get_parameters().front()->get_type();
457                Type * t2 = ftype->get_parameters().back()->get_type();
458                PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
459                assert( ptrType );
460
461                if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
462                        return function;
463                } else {
464                        return 0;
465                }
466        }
[2b46a13]467}
Note: See TracBrowser for help on using the repository browser.