source: src/InitTweak/InitTweak.cc @ 79970ed

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 79970ed was 79970ed, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

implement warnings for missing struct member constructor calls, remove bad clones

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