source: src/InitTweak/InitTweak.cc @ 8ff178d

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 8ff178d was 9b4f329, checked in by Aaron Moss <a3moss@…>, 5 years ago

Finished porting AST::Expr subclasses

  • Property mode set to 100644
File size: 26.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 "AST/Expr.hpp"
8#include "AST/Stmt.hpp"
9#include "AST/Type.hpp"
10#include "Common/PassVisitor.h"
11#include "Common/SemanticError.h"  // for SemanticError
12#include "Common/UniqueName.h"     // for UniqueName
13#include "Common/utility.h"        // for toString, deleteAll, maybeClone
14#include "GenPoly/GenPoly.h"       // for getFunctionType
15#include "InitTweak.h"
16#include "Parser/LinkageSpec.h"    // for Spec, isBuiltin, Intrinsic
17#include "ResolvExpr/typeops.h"    // for typesCompatibleIgnoreQualifiers
18#include "SymTab/Autogen.h"
19#include "SymTab/Indexer.h"        // for Indexer
20#include "SynTree/Attribute.h"     // for Attribute
21#include "SynTree/Constant.h"      // for Constant
22#include "SynTree/Declaration.h"   // for ObjectDecl, DeclarationWithType
23#include "SynTree/Expression.h"    // for Expression, UntypedExpr, Applicati...
24#include "SynTree/Initializer.h"   // for Initializer, ListInit, Designation
25#include "SynTree/Label.h"         // for Label
26#include "SynTree/Statement.h"     // for CompoundStmt, ExprStmt, BranchStmt
27#include "SynTree/Type.h"          // for FunctionType, ArrayType, PointerType
28#include "SynTree/Visitor.h"       // for Visitor, maybeAccept
29#include "Tuples/Tuples.h"         // for Tuples::isTtype
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() { delete arg; }
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                deleteAll( indices );
170                indices.clear();
171        }
172
173        bool InitExpander::addReference() {
174                bool added = false;
175                for ( Expression *& expr : cur ) {
176                        expr = new AddressExpr( expr );
177                        added = true;
178                }
179                return added;
180        }
181
182        namespace {
183                /// given index i, dimension d, initializer init, and callExpr f, generates
184                ///   if (i < d) f(..., init)
185                ///   ++i;
186                /// so that only elements within the range of the array are constructed
187                template< typename OutIterator >
188                void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
189                        UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
190                        cond->get_args().push_back( index->clone() );
191                        cond->get_args().push_back( dimension->clone() );
192
193                        std::list< Expression * > args = makeInitList( init );
194                        callExpr->get_args().splice( callExpr->get_args().end(), args );
195
196                        *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
197
198                        UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
199                        increment->get_args().push_back( index->clone() );
200                        *out++ = new ExprStmt( increment );
201                }
202
203                template< typename OutIterator >
204                void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
205                        if ( idx == idxEnd ) return;
206                        Expression * index = *idx++;
207                        assert( idx != idxEnd );
208                        Expression * dimension = *idx++;
209
210                        // xxx - may want to eventually issue a warning here if we can detect
211                        // that the number of elements exceeds to dimension of the array
212                        if ( idx == idxEnd ) {
213                                if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
214                                        for ( Initializer * init : *listInit ) {
215                                                buildCallExpr( callExpr->clone(), index, dimension, init, out );
216                                        }
217                                } else {
218                                        buildCallExpr( callExpr->clone(), index, dimension, init, out );
219                                }
220                        } else {
221                                std::list< Statement * > branches;
222
223                                unsigned long cond = 0;
224                                ListInit * listInit = dynamic_cast< ListInit * >( init );
225                                if ( ! listInit ) {
226                                        // xxx - this shouldn't be an error, but need a way to
227                                        // terminate without creating output, so should catch this error
228                                        SemanticError( init->location, "unbalanced list initializers" );
229                                }
230
231                                static UniqueName targetLabel( "L__autogen__" );
232                                Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
233                                for ( Initializer * init : *listInit ) {
234                                        Expression * condition;
235                                        // check for designations
236                                        // if ( init-> ) {
237                                                condition = new ConstantExpr( Constant::from_ulong( cond ) );
238                                                ++cond;
239                                        // } else {
240                                        //      condition = // ... take designation
241                                        //      cond = // ... take designation+1
242                                        // }
243                                        std::list< Statement * > stmts;
244                                        build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
245                                        stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
246                                        CaseStmt * caseStmt = new CaseStmt( condition, stmts );
247                                        branches.push_back( caseStmt );
248                                }
249                                *out++ = new SwitchStmt( index->clone(), branches );
250                                *out++ = new NullStmt( { switchLabel } );
251                        }
252                }
253        }
254
255        // if array came with an initializer list: initialize each element
256        // may have more initializers than elements in the array - need to check at each index that
257        // we haven't exceeded size.
258        // may have fewer initializers than elements in the array - need to default construct
259        // remaining elements.
260        // To accomplish this, generate switch statement, consuming all of expander's elements
261        Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
262                if ( ! init ) return nullptr;
263                CompoundStmt * block = new CompoundStmt();
264                build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
265                if ( block->get_kids().empty() ) {
266                        delete block;
267                        return nullptr;
268                } else {
269                        init = nullptr; // init was consumed in creating the list init
270                        return block;
271                }
272        }
273
274        Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
275                return nullptr;
276        }
277
278        Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
279                return expander->buildListInit( dst, indices );
280        }
281
282        Type * getTypeofThis( FunctionType * ftype ) {
283                assertf( ftype, "getTypeofThis: nullptr ftype" );
284                ObjectDecl * thisParam = getParamThis( ftype );
285                ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
286                return refType->base;
287        }
288
289        ObjectDecl * getParamThis( FunctionType * ftype ) {
290                assertf( ftype, "getParamThis: nullptr ftype" );
291                auto & params = ftype->parameters;
292                assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
293                return strict_dynamic_cast< ObjectDecl * >( params.front() );
294        }
295
296        bool tryConstruct( DeclarationWithType * dwt ) {
297                ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
298                if ( ! objDecl ) return false;
299                return (objDecl->get_init() == nullptr ||
300                                ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
301                        && ! objDecl->get_storageClasses().is_extern
302                        && isConstructable( objDecl->type );
303        }
304
305        bool isConstructable( Type * type ) {
306                return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
307        }
308
309        struct CallFinder {
310                CallFinder( const std::list< std::string > & names ) : names( names ) {}
311
312                void postvisit( ApplicationExpr * appExpr ) {
313                        handleCallExpr( appExpr );
314                }
315
316                void postvisit( UntypedExpr * untypedExpr ) {
317                        handleCallExpr( untypedExpr );
318                }
319
320                std::list< Expression * > * matches;
321        private:
322                const std::list< std::string > names;
323
324                template< typename CallExpr >
325                void handleCallExpr( CallExpr * expr ) {
326                        std::string fname = getFunctionName( expr );
327                        if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
328                                matches->push_back( expr );
329                        }
330                }
331        };
332
333        void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
334                static PassVisitor<CallFinder> finder( std::list< std::string >{ "?{}", "^?{}" } );
335                finder.pass.matches = &matches;
336                maybeAccept( stmt, finder );
337        }
338
339        Expression * getCtorDtorCall( Statement * stmt ) {
340                std::list< Expression * > matches;
341                collectCtorDtorCalls( stmt, matches );
342                assert( matches.size() <= 1 );
343                return matches.size() == 1 ? matches.front() : nullptr;
344        }
345
346        namespace {
347                DeclarationWithType * getCalledFunction( Expression * expr );
348
349                template<typename CallExpr>
350                DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
351                        // (*f)(x) => should get "f"
352                        std::string name = getFunctionName( expr );
353                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
354                        assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
355                        return getCalledFunction( expr->get_args().front() );
356                }
357
358                DeclarationWithType * getCalledFunction( Expression * expr ) {
359                        assert( expr );
360                        if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
361                                return varExpr->var;
362                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
363                                return memberExpr->member;
364                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
365                                return getCalledFunction( castExpr->arg );
366                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
367                                return handleDerefCalledFunction( untypedExpr );
368                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
369                                return handleDerefCalledFunction( appExpr );
370                        } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
371                                return getCalledFunction( addrExpr->arg );
372                        } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
373                                return getCalledFunction( commaExpr->arg2 );
374                        }
375                        return nullptr;
376                }
377        }
378
379        DeclarationWithType * getFunction( Expression * expr ) {
380                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
381                        return getCalledFunction( appExpr->get_function() );
382                } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
383                        return getCalledFunction( untyped->get_function() );
384                }
385                assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
386        }
387
388        ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
389                ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
390                if ( ! appExpr ) return nullptr;
391                DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
392                assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
393                // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
394                // will call all member dtors, and some members may have a user defined dtor.
395                return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
396        }
397
398        namespace {
399                template <typename Predicate>
400                bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
401                        std::list< Expression * > callExprs;
402                        collectCtorDtorCalls( stmt, callExprs );
403                        // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
404                        return std::all_of( callExprs.begin(), callExprs.end(), pred);
405                }
406        }
407
408        bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
409                return allofCtorDtor( stmt, []( Expression * callExpr ){
410                        if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
411                                FunctionType *funcType = GenPoly::getFunctionType( appExpr->function->result );
412                                assert( funcType );
413                                return funcType->get_parameters().size() == 1;
414                        }
415                        return false;
416                });
417        }
418
419        bool isIntrinsicCallStmt( Statement * stmt ) {
420                return allofCtorDtor( stmt, []( Expression * callExpr ) {
421                        return isIntrinsicCallExpr( callExpr );
422                });
423        }
424
425        namespace {
426                template<typename CallExpr>
427                Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
428                        if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
429                        for ( Expression *& arg : callExpr->get_args() ) {
430                                if ( pos == 0 ) return arg;
431                                pos--;
432                        }
433                        assert( false );
434                }
435
436                // template<typename CallExpr>
437                // const ast::Expr * callArg( const CallExpr * call, unsigned int pos ) {
438                //      if( pos >= call->args.size() ) {
439                //              assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.",
440                //                      pos, toString( call ).c_str() );
441                //      }
442                //      for ( const ast::Expr * arg : call->args ) {
443                //              if ( pos == 0 ) return arg;
444                //              --pos;
445                //      }
446                //      assert( false );
447                // }
448        }
449
450        Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
451                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
452                        return callArg( appExpr, pos );
453                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
454                        return callArg( untypedExpr, pos );
455                } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
456                        std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
457                        assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
458                        ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
459                        TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
460                        assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
461                        return getCallArg( tuple->get_exprs().front(), pos );
462                } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
463                        return getCallArg( copyCtor->callExpr, pos );
464                } else {
465                        assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
466                }
467        }
468        const ast::Expr * getCallArg( const ast::Expr * call, unsigned pos ) {
469                assert(!"implemented; needs to build AST/Expr.cpp");
470                // if ( auto app = dynamic_cast< const ast::ApplicationExpr * >( call ) ) {
471                //      return callArg( app, pos );
472                // } else if ( auto untyped = dynamic_cast< const ast::UntypedExpr * >( call ) ) {
473                //      return callArg( untyped, pos );
474                // } else if ( auto tupleAssn = dynamic_cast< const ast::TupleAssignExpr * >( call ) ) {
475                //      const std::list<ast::ptr<ast::Stmt>>& stmts = tupleAssn->stmtExpr->stmts->kids;
476                //      assertf( ! stmts.empty(), "TupleAssignExpr missing statements." );
477                //      const ExprStmt * stmt = strict_dynamic_cast< const ast::ExprStmt * >( stmts.back() );
478                //      const TupleExpr * tuple = strict_dynamic_cast< const ast::TupleExpr * >( stmt->expr );
479                //      assertf( ! tuple->exprs.empty(), "TupleAssignExpr has empty tuple expr.");
480                //      return getCallArg( tuple->exprs.front(), pos );
481                // } else if ( auto ctor = dynamic_cast< const ast::ImplicitCopyCtorExpr * >( call ) ) {
482                //      return getCallArg( ctor->callExpr, pos );
483                // } else {
484                //      assertf( false, "Unexpected expression type passed to getCallArg: %s",
485                //              toString( call ).c_str() );
486                // }
487        }
488
489        namespace {
490                std::string funcName( Expression * func );
491
492                template<typename CallExpr>
493                std::string handleDerefName( CallExpr * expr ) {
494                        // (*f)(x) => should get name "f"
495                        std::string name = getFunctionName( expr );
496                        assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
497                        assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
498                        return funcName( expr->get_args().front() );
499                }
500
501                std::string funcName( Expression * func ) {
502                        if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
503                                return nameExpr->get_name();
504                        } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
505                                return varExpr->get_var()->get_name();
506                        }       else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
507                                return funcName( castExpr->get_arg() );
508                        } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
509                                return memberExpr->get_member()->get_name();
510                        } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
511                                return funcName( memberExpr->get_member() );
512                        } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
513                                return handleDerefName( untypedExpr );
514                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
515                                return handleDerefName( appExpr );
516                        } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
517                                return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
518                        } else {
519                                assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
520                        }
521                }
522        }
523
524        std::string getFunctionName( Expression * expr ) {
525                // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
526                // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
527                // can't possibly do anything reasonable.
528                if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
529                        return funcName( appExpr->get_function() );
530                } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
531                        return funcName( untypedExpr->get_function() );
532                } else {
533                        std::cerr << expr << std::endl;
534                        assertf( false, "Unexpected expression type passed to getFunctionName" );
535                }
536        }
537
538        Type * getPointerBase( Type * type ) {
539                if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
540                        return ptrType->get_base();
541                } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
542                        return arrayType->get_base();
543                } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
544                        return refType->get_base();
545                } else {
546                        return nullptr;
547                }
548        }
549        const ast::Type* getPointerBase( const ast::Type* t ) {
550                assert(!"needs to build Type.cpp before inclusion");
551                // if ( const auto * p = dynamic_cast< const ast::PointerType * >( t ) ) {
552                //      return p->base;
553                // } else if ( const auto * a = dynamic_cast< const ast::ArrayType * >( t ) ) {
554                //      return a->base;
555                // } else if ( const auto * r = dynamic_cast< const ast::ReferenceType * >( t ) ) {
556                //      return r->base;
557                // } else return nullptr;
558        }
559
560        Type * isPointerType( Type * type ) {
561                if ( getPointerBase( type ) ) return type;
562                else return nullptr;
563        }
564
565        ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
566                static FunctionDecl * assign = nullptr;
567                if ( ! assign ) {
568                        // temporary? Generate a fake assignment operator to represent bitwise assignments.
569                        // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
570                        TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
571                        assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
572                }
573                if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
574                        for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
575                                dst = new AddressExpr( dst );
576                        }
577                } else {
578                        dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
579                }
580                if ( dynamic_cast< ReferenceType * >( src->result ) ) {
581                        for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
582                                src = new AddressExpr( src );
583                        }
584                        // src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
585                }
586                return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
587        }
588
589        struct ConstExprChecker : public WithShortCircuiting {
590                // most expressions are not const expr
591                void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
592
593                void previsit( AddressExpr *addressExpr ) {
594                        visit_children = false;
595
596                        // address of a variable or member expression is constexpr
597                        Expression * arg = addressExpr->get_arg();
598                        if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
599                }
600
601                // these expressions may be const expr, depending on their children
602                void previsit( SizeofExpr * ) {}
603                void previsit( AlignofExpr * ) {}
604                void previsit( UntypedOffsetofExpr * ) {}
605                void previsit( OffsetofExpr * ) {}
606                void previsit( OffsetPackExpr * ) {}
607                void previsit( AttrExpr * ) {}
608                void previsit( CommaExpr * ) {}
609                void previsit( LogicalExpr * ) {}
610                void previsit( ConditionalExpr * ) {}
611                void previsit( CastExpr * ) {}
612                void previsit( ConstantExpr * ) {}
613
614                void previsit( VariableExpr * varExpr ) {
615                        visit_children = false;
616
617                        if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
618                                long long int value;
619                                if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
620                                        // enumerators are const expr
621                                        return;
622                                }
623                        }
624                        isConstExpr = false;
625                }
626
627                bool isConstExpr = true;
628        };
629
630        bool isConstExpr( Expression * expr ) {
631                if ( expr ) {
632                        PassVisitor<ConstExprChecker> checker;
633                        expr->accept( checker );
634                        return checker.pass.isConstExpr;
635                }
636                return true;
637        }
638
639        bool isConstExpr( Initializer * init ) {
640                if ( init ) {
641                        PassVisitor<ConstExprChecker> checker;
642                        init->accept( checker );
643                        return checker.pass.isConstExpr;
644                } // if
645                // for all intents and purposes, no initializer means const expr
646                return true;
647        }
648
649        bool isConstructor( const std::string & str ) { return str == "?{}"; }
650        bool isDestructor( const std::string & str ) { return str == "^?{}"; }
651        bool isAssignment( const std::string & str ) { return str == "?=?"; }
652        bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
653        bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
654
655        FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
656                FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
657                if ( ! function ) return nullptr;
658                if ( function->name != fname ) return nullptr;
659                FunctionType * ftype = function->type;
660                if ( ftype->parameters.size() != 2 ) return nullptr;
661
662                Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
663                Type * t2 = ftype->parameters.back()->get_type();
664                assert( t1 );
665
666                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
667                        return function;
668                } else {
669                        return nullptr;
670                }
671        }
672
673        FunctionDecl * isAssignment( Declaration * decl ) {
674                return isCopyFunction( decl, "?=?" );
675        }
676        FunctionDecl * isDestructor( Declaration * decl ) {
677                if ( isDestructor( decl->get_name() ) ) {
678                        return dynamic_cast< FunctionDecl * >( decl );
679                }
680                return nullptr;
681        }
682        FunctionDecl * isDefaultConstructor( Declaration * decl ) {
683                if ( isConstructor( decl->name ) ) {
684                        if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
685                                if ( func->type->parameters.size() == 1 ) {
686                                        return func;
687                                }
688                        }
689                }
690                return nullptr;
691        }
692        FunctionDecl * isCopyConstructor( Declaration * decl ) {
693                return isCopyFunction( decl, "?{}" );
694        }
695}
Note: See TracBrowser for help on using the repository browser.