source: src/InitTweak/InitTweak.cc @ ff29f08

new-envwith_gc
Last change on this file since ff29f08 was 1cdfa82, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge remote-tracking branch 'origin/master' into with_gc

  • Property mode set to 100644
File size: 24.4 KB
Line 
1#include <algorithm>               // for find, all_of
2#include <cassert>                 // for assertf, assert, strict_dynamic_cast
3#include <iostream>                // for ostream, cerr, endl
4#include <iterator>                // for back_insert_iterator, back_inserter
5#include <memory>                  // for __shared_ptr
6
7#include "Common/GC.h"             // for new_static_root
8#include "Common/PassVisitor.h"
9#include "Common/SemanticError.h"  // for SemanticError
10#include "Common/UniqueName.h"     // for UniqueName
11#include "Common/utility.h"        // for toString, deleteAll, maybeClone
12#include "GenPoly/GenPoly.h"       // for getFunctionType
13#include "InitTweak.h"
14#include "Parser/LinkageSpec.h"    // for Spec, isBuiltin, Intrinsic
15#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
16#include "SymTab/Autogen.h"
17#include "SymTab/Indexer.h"        // for Indexer
18#include "SynTree/Attribute.h"     // for Attribute
19#include "SynTree/Constant.h"      // for Constant
20#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
21#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
22#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
23#include "SynTree/Label.h"         // for Label
24#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
25#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
26#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
27#include "Tuples/Tuples.h"         // for Tuples::isTtype
28
29class UntypedValofExpr;
30
31namespace InitTweak {
32        namespace {
33                struct HasDesignations : public WithShortCircuiting {
34                        bool hasDesignations = false;
35
36                        void previsit( BaseSyntaxNode * ) {
37                                // short circuit if we already know there are designations
38                                if ( hasDesignations ) visit_children = false;
39                        }
40
41                        void previsit( Designation * des ) {
42                                // short circuit if we already know there are designations
43                                if ( hasDesignations ) visit_children = false;
44                                else if ( ! des->get_designators().empty() ) {
45                                        hasDesignations = true;
46                                        visit_children = false;
47                                }
48                        }
49                };
50
51                struct InitDepthChecker : public WithGuards {
52                        bool depthOkay = true;
53                        Type * type;
54                        int curDepth = 0, maxDepth = 0;
55                        InitDepthChecker( Type * type ) : type( type ) {
56                                Type * t = type;
57                                while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
58                                        maxDepth++;
59                                        t = at->get_base();
60                                }
61                                maxDepth++;
62                        }
63                        void previsit( ListInit * ) {
64                                curDepth++;
65                                GuardAction( [this]() { curDepth--; } );
66                                if ( curDepth > maxDepth ) depthOkay = false;
67                        }
68                };
69
70                struct InitFlattener : public WithShortCircuiting {
71                        void previsit( SingleInit * singleInit ) {
72                                visit_children = false;
73                                argList.push_back( singleInit->value->clone() );
74                        }
75                        std::list< Expression * > argList;
76                };
77
78        }
79
80        std::list< Expression * > makeInitList( Initializer * init ) {
81                PassVisitor<InitFlattener> flattener;
82                maybeAccept( init, flattener );
83                return flattener.pass.argList;
84        }
85
86        bool isDesignated( Initializer * init ) {
87                PassVisitor<HasDesignations> finder;
88                maybeAccept( init, finder );
89                return finder.pass.hasDesignations;
90        }
91
92        bool checkInitDepth( ObjectDecl * objDecl ) {
93                PassVisitor<InitDepthChecker> checker( objDecl->type );
94                maybeAccept( objDecl->init, checker );
95                return checker.pass.depthOkay;
96        }
97
98        class InitExpander::ExpanderImpl {
99        public:
100                virtual ~ExpanderImpl() = default;
101                virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
102                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
103        };
104
105        class InitImpl : public InitExpander::ExpanderImpl {
106        public:
107                InitImpl( Initializer * init ) : init( init ) {}
108                virtual ~InitImpl() = default;
109
110                virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
111                        // this is wrong, but just a placeholder for now
112                        // if ( ! flattened ) flatten( indices );
113                        // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
114                        return makeInitList( init );
115                }
116
117                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
118        private:
119                Initializer * init;
120        };
121
122        class ExprImpl : public InitExpander::ExpanderImpl {
123        public:
124                ExprImpl( Expression * expr ) : arg( expr ) {}
125                virtual ~ExprImpl() = default;
126
127                virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
128                        std::list< Expression * > ret;
129                        Expression * expr = maybeClone( arg );
130                        if ( expr ) {
131                                for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
132                                        // go through indices and layer on subscript exprs ?[?]
133                                        ++it;
134                                        UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
135                                        subscriptExpr->get_args().push_back( expr );
136                                        subscriptExpr->get_args().push_back( (*it)->clone() );
137                                        expr = subscriptExpr;
138                                }
139                                ret.push_back( expr );
140                        }
141                        return ret;
142                }
143
144                virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
145        private:
146                Expression * arg;
147        };
148
149        InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
150
151        InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
152
153        std::list< Expression * > InitExpander::operator*() {
154                return cur;
155        }
156
157        InitExpander & InitExpander::operator++() {
158                cur = expander->next( indices );
159                return *this;
160        }
161
162        // use array indices list to build switch statement
163        void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
164                indices.push_back( index );
165                indices.push_back( dimension );
166        }
167
168        void InitExpander::clearArrayIndices() {
169                indices.clear();
170        }
171
172        bool InitExpander::addReference() {
173                bool added = false;
174                for ( Expression *& expr : cur ) {
175                        expr = new AddressExpr( expr );
176                        added = true;
177                }
178                return added;
179        }
180
181        namespace {
182                /// given index i, dimension d, initializer init, and callExpr f, generates
183                ///   if (i < d) f(..., init)
184                ///   ++i;
185                /// so that only elements within the range of the array are constructed
186                template< typename OutIterator >
187                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
188                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
189                        cond->get_args().push_back( index->clone() );
190                        cond->get_args().push_back( dimension->clone() );
191
192                        std::list< Expression * > args = makeInitList( init );
193                        callExpr->get_args().splice( callExpr->get_args().end(), args );
194
195                        *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
196
197                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
198                        increment->get_args().push_back( index->clone() );
199                        *out++ = new ExprStmt( increment );
200                }
201
202                template< typename OutIterator >
203                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
204                        if ( idx == idxEnd ) return;
205                        Expression * index = *idx++;
206                        assert( idx != idxEnd );
207                        Expression * dimension = *idx++;
208
209                        // xxx - may want to eventually issue a warning here if we can detect
210                        // that the number of elements exceeds to dimension of the array
211                        if ( idx == idxEnd ) {
212                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
213                                        for ( Initializer * init : *listInit ) {
214                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
215                                        }
216                                } else {
217                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
218                                }
219                        } else {
220                                std::list< Statement * > branches;
221
222                                unsigned long cond = 0;
223                                ListInit * listInit = dynamic_cast< ListInit * >( init );
224                                if ( ! listInit ) {
225                                        // xxx - this shouldn't be an error, but need a way to
226                                        // terminate without creating output, so should catch this error
227                                        SemanticError( init->location, "unbalanced list initializers" );
228                                }
229
230                                static UniqueName targetLabel( "L__autogen__" );
231                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
232                                for ( Initializer * init : *listInit ) {
233                                        Expression * condition;
234                                        // check for designations
235                                        // if ( init-> ) {
236                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
237                                                ++cond;
238                                        // } else {
239                                        //      condition = // ... take designation
240                                        //      cond = // ... take designation+1
241                                        // }
242                                        std::list< Statement * > stmts;
243                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
244                                        stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
245                                        CaseStmt * caseStmt = new CaseStmt( condition, stmts );
246                                        branches.push_back( caseStmt );
247                                }
248                                *out++ = new SwitchStmt( index->clone(), branches );
249                                *out++ = new NullStmt( { switchLabel } );
250                        }
251                }
252        }
253
254        // if array came with an initializer list: initialize each element
255        // may have more initializers than elements in the array - need to check at each index that
256        // we haven't exceeded size.
257        // may have fewer initializers than elements in the array - need to default construct
258        // remaining elements.
259        // To accomplish this, generate switch statement, consuming all of expander's elements
260        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
261                if ( ! init ) return nullptr;
262                CompoundStmt * block = new CompoundStmt();
263                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
264                if ( block->get_kids().empty() ) {
265                        return nullptr;
266                } else {
267                        init = nullptr; // init was consumed in creating the list init
268                        return block;
269                }
270        }
271
272        Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
273                return nullptr;
274        }
275
276        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
277                return expander->buildListInit( dst, indices );
278        }
279
280        Type * getTypeofThis( FunctionType * ftype ) {
281                assertf( ftype, "getTypeofThis: nullptr ftype" );
282                ObjectDecl * thisParam = getParamThis( ftype );
283                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
284                return refType->base;
285        }
286
287        ObjectDecl * getParamThis( FunctionType * ftype ) {
288                assertf( ftype, "getParamThis: nullptr ftype" );
289                auto & params = ftype->parameters;
290                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
291                return strict_dynamic_cast< ObjectDecl * >( params.front() );
292        }
293
294        bool tryConstruct( DeclarationWithType * dwt ) {
295                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
296                if ( ! objDecl ) return false;
297                return (objDecl->get_init() == nullptr ||
298                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
299                        && ! objDecl->get_storageClasses().is_extern
300                        && isConstructable( objDecl->type );
301        }
302
303        bool isConstructable( Type * type ) {
304                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
305        }
306
307        struct CallFinder {
308                CallFinder( const std::list< std::string > & names ) : names( names ) {}
309
310                void postvisit( ApplicationExpr * appExpr ) {
311                        handleCallExpr( appExpr );
312                }
313
314                void postvisit( UntypedExpr * untypedExpr ) {
315                        handleCallExpr( untypedExpr );
316                }
317
318                std::list< Expression * > * matches;
319        private:
320                const std::list< std::string > names;
321
322                template< typename CallExpr >
323                void handleCallExpr( CallExpr * expr ) {
324                        std::string fname = getFunctionName( expr );
325                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
326                                matches->push_back( expr );
327                        }
328                }
329        };
330
331        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
332                static PassVisitor<CallFinder> finder( std::list< std::string >{ "?{}", "^?{}" } );
333                finder.pass.matches = &matches;
334                maybeAccept( stmt, finder );
335        }
336
337        Expression * getCtorDtorCall( Statement * stmt ) {
338                std::list< Expression * > matches;
339                collectCtorDtorCalls( stmt, matches );
340                assert( matches.size() <= 1 );
341                return matches.size() == 1 ? matches.front() : nullptr;
342        }
343
344        namespace {
345                DeclarationWithType * getCalledFunction( Expression * expr );
346
347                template<typename CallExpr>
348                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
349                        // (*f)(x) => should get "f"
350                        std::string name = getFunctionName( expr );
351                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
352                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
353                        return getCalledFunction( expr->get_args().front() );
354                }
355
356                DeclarationWithType * getCalledFunction( Expression * expr ) {
357                        assert( expr );
358                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
359                                return varExpr->var;
360                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
361                                return memberExpr->member;
362                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
363                                return getCalledFunction( castExpr->arg );
364                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
365                                return handleDerefCalledFunction( untypedExpr );
366                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
367                                return handleDerefCalledFunction( appExpr );
368                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
369                                return getCalledFunction( addrExpr->arg );
370                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
371                                return getCalledFunction( commaExpr->arg2 );
372                        }
373                        return nullptr;
374                }
375        }
376
377        DeclarationWithType * getFunction( Expression * expr ) {
378                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
379                        return getCalledFunction( appExpr->get_function() );
380                } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
381                        return getCalledFunction( untyped->get_function() );
382                }
383                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
384        }
385
386        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
387                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
388                if ( ! appExpr ) return nullptr;
389                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
390                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
391                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
392                // will call all member dtors, and some members may have a user defined dtor.
393                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
394        }
395
396        namespace {
397                template <typename Predicate>
398                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
399                        std::list< Expression * > callExprs;
400                        collectCtorDtorCalls( stmt, callExprs );
401                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
402                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
403                }
404        }
405
406        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
407                return allofCtorDtor( stmt, []( Expression * callExpr ){
408                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
409                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_result() );
410                                assert( funcType );
411                                return funcType->get_parameters().size() == 1;
412                        }
413                        return false;
414                });
415        }
416
417        bool isIntrinsicCallStmt( Statement * stmt ) {
418                return allofCtorDtor( stmt, []( Expression * callExpr ) {
419                        return isIntrinsicCallExpr( callExpr );
420                });
421        }
422
423        namespace {
424                template<typename CallExpr>
425                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
426                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
427                        for ( Expression *& arg : callExpr->get_args() ) {
428                                if ( pos == 0 ) return arg;
429                                pos--;
430                        }
431                        assert( false );
432                }
433        }
434
435        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
436                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
437                        return callArg( appExpr, pos );
438                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
439                        return callArg( untypedExpr, pos );
440                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
441                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
442                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
443                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
444                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
445                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
446                        return getCallArg( tuple->get_exprs().front(), pos );
447                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
448                        return getCallArg( copyCtor->callExpr, pos );
449                } else {
450                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
451                }
452        }
453
454        namespace {
455                std::string funcName( Expression * func );
456
457                template<typename CallExpr>
458                std::string handleDerefName( CallExpr * expr ) {
459                        // (*f)(x) => should get name "f"
460                        std::string name = getFunctionName( expr );
461                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
462                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
463                        return funcName( expr->get_args().front() );
464                }
465
466                std::string funcName( Expression * func ) {
467                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
468                                return nameExpr->get_name();
469                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
470                                return varExpr->get_var()->get_name();
471                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
472                                return funcName( castExpr->get_arg() );
473                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
474                                return memberExpr->get_member()->get_name();
475                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
476                                return funcName( memberExpr->get_member() );
477                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
478                                return handleDerefName( untypedExpr );
479                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
480                                return handleDerefName( appExpr );
481                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
482                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
483                        } else {
484                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
485                        }
486                }
487        }
488
489        std::string getFunctionName( Expression * expr ) {
490                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
491                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
492                // can't possibly do anything reasonable.
493                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
494                        return funcName( appExpr->get_function() );
495                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
496                        return funcName( untypedExpr->get_function() );
497                } else {
498                        std::cerr << expr << std::endl;
499                        assertf( false, "Unexpected expression type passed to getFunctionName" );
500                }
501        }
502
503        Type * getPointerBase( Type * type ) {
504                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
505                        return ptrType->get_base();
506                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
507                        return arrayType->get_base();
508                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
509                        return refType->get_base();
510                } else {
511                        return nullptr;
512                }
513        }
514
515        Type * isPointerType( Type * type ) {
516                if ( getPointerBase( type ) ) return type;
517                else return nullptr;
518        }
519
520        ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
521                static FunctionDecl * assign = nullptr;
522                if ( ! assign ) {
523                        // temporary? Generate a fake assignment operator to represent bitwise assignments.
524                        // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
525                        TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
526                        assign = new_static_root<FunctionDecl>( 
527                                "?=?", noStorageClasses, LinkageSpec::Intrinsic, 
528                                SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
529                }
530                if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
531                        for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
532                                dst = new AddressExpr( dst );
533                        }
534                } else {
535                        dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
536                }
537                if ( dynamic_cast< ReferenceType * >( src->result ) ) {
538                        for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
539                                src = new AddressExpr( src );
540                        }
541                        // src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
542                }
543                return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
544        }
545
546        struct ConstExprChecker : public WithShortCircuiting {
547                // most expressions are not const expr
548                void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
549
550                void previsit( AddressExpr *addressExpr ) {
551                        visit_children = false;
552
553                        // address of a variable or member expression is constexpr
554                        Expression * arg = addressExpr->get_arg();
555                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
556                }
557
558                // these expressions may be const expr, depending on their children
559                void previsit( SizeofExpr * ) {}
560                void previsit( AlignofExpr * ) {}
561                void previsit( UntypedOffsetofExpr * ) {}
562                void previsit( OffsetofExpr * ) {}
563                void previsit( OffsetPackExpr * ) {}
564                void previsit( AttrExpr * ) {}
565                void previsit( CommaExpr * ) {}
566                void previsit( LogicalExpr * ) {}
567                void previsit( ConditionalExpr * ) {}
568                void previsit( CastExpr * ) {}
569                void previsit( ConstantExpr * ) {}
570
571                void previsit( VariableExpr * varExpr ) {
572                        visit_children = false;
573
574                        if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
575                                long long int value;
576                                if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
577                                        // enumerators are const expr
578                                        return;
579                                }
580                        }
581                        isConstExpr = false;
582                }
583
584                bool isConstExpr = true;
585        };
586
587        bool isConstExpr( Expression * expr ) {
588                if ( expr ) {
589                        PassVisitor<ConstExprChecker> checker;
590                        expr->accept( checker );
591                        return checker.pass.isConstExpr;
592                }
593                return true;
594        }
595
596        bool isConstExpr( Initializer * init ) {
597                if ( init ) {
598                        PassVisitor<ConstExprChecker> checker;
599                        init->accept( checker );
600                        return checker.pass.isConstExpr;
601                } // if
602                // for all intents and purposes, no initializer means const expr
603                return true;
604        }
605
606        bool isConstructor( const std::string & str ) { return str == "?{}"; }
607        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
608        bool isAssignment( const std::string & str ) { return str == "?=?"; }
609        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
610        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
611
612        FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
613                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
614                if ( ! function ) return nullptr;
615                if ( function->name != fname ) return nullptr;
616                FunctionType * ftype = function->type;
617                if ( ftype->parameters.size() != 2 ) return nullptr;
618
619                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
620                Type * t2 = ftype->parameters.back()->get_type();
621                assert( t1 );
622
623                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
624                        return function;
625                } else {
626                        return nullptr;
627                }
628        }
629
630        FunctionDecl * isAssignment( Declaration * decl ) {
631                return isCopyFunction( decl, "?=?" );
632        }
633        FunctionDecl * isDestructor( Declaration * decl ) {
634                if ( isDestructor( decl->get_name() ) ) {
635                        return dynamic_cast< FunctionDecl * >( decl );
636                }
637                return nullptr;
638        }
639        FunctionDecl * isDefaultConstructor( Declaration * decl ) {
640                if ( isConstructor( decl->name ) ) {
641                        if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
642                                if ( func->type->parameters.size() == 1 ) {
643                                        return func;
644                                }
645                        }
646                }
647                return nullptr;
648        }
649        FunctionDecl * isCopyConstructor( Declaration * decl ) {
650                return isCopyFunction( decl, "?{}" );
651        }
652}
Note: See TracBrowser for help on using the repository browser.