source: src/ResolvExpr/Resolver.cc @ 7eabc25

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

Merge branch 'fix-memory-error' into ctor

Conflicts:

src/CodeGen/CodeGenerator.cc
src/Makefile.in
src/Parser/DeclarationNode.cc
src/Parser/ParseNode.h
src/Parser/TypeData.cc
src/Parser/parser.cc
src/Parser/parser.yy
src/ResolvExpr/Resolver.cc
src/SymTab/Validate.cc
src/SynTree/Declaration.h
src/SynTree/Mutator.cc
src/SynTree/Mutator.h
src/SynTree/SynTree.h
src/SynTree/Visitor.cc
src/SynTree/Visitor.h
src/libcfa/prelude.cf

  • Property mode set to 100644
File size: 18.2 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Resolver.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Rob Schluntz
12// Last Modified On : Mon Apr 04 17:11:54 2016
13// Update Count     : 203
14//
15
16#include "Resolver.h"
17#include "AlternativeFinder.h"
18#include "Alternative.h"
19#include "RenameVars.h"
20#include "ResolveTypeof.h"
21#include "SynTree/Statement.h"
22#include "SynTree/Type.h"
23#include "SynTree/Expression.h"
24#include "SynTree/Initializer.h"
25#include "SymTab/Indexer.h"
26#include "Common/utility.h"
27
28#include <iostream>
29using namespace std;
30
31namespace ResolvExpr {
32        class Resolver : public SymTab::Indexer {
33          public:
34                Resolver() : SymTab::Indexer( false ), switchType( 0 ) {}
35
36                virtual void visit( FunctionDecl *functionDecl );
37                virtual void visit( ObjectDecl *functionDecl );
38                virtual void visit( TypeDecl *typeDecl );
39
40                virtual void visit( ArrayType * at );
41
42                virtual void visit( ExprStmt *exprStmt );
43                virtual void visit( AsmExpr *asmExpr );
44                virtual void visit( AsmStmt *asmStmt );
45                virtual void visit( IfStmt *ifStmt );
46                virtual void visit( WhileStmt *whileStmt );
47                virtual void visit( ForStmt *forStmt );
48                virtual void visit( SwitchStmt *switchStmt );
49                virtual void visit( ChooseStmt *switchStmt );
50                virtual void visit( CaseStmt *caseStmt );
51                virtual void visit( BranchStmt *branchStmt );
52                virtual void visit( ReturnStmt *returnStmt );
53
54                virtual void visit( SingleInit *singleInit );
55                virtual void visit( ListInit *listInit );
56                virtual void visit( ConstructorInit *ctorInit );
57          private:
58        typedef std::list< Initializer * >::iterator InitIterator;
59
60          void resolveAggrInit( AggregateDecl *, InitIterator &, InitIterator & );
61          void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator & );
62          void fallbackInit( ConstructorInit * ctorInit );
63
64                std::list< Type * > functionReturn;
65                Type *initContext;
66                Type *switchType;
67        };
68
69        void resolve( std::list< Declaration * > translationUnit ) {
70                Resolver resolver;
71                acceptAll( translationUnit, resolver );
72#if 0
73                resolver.print( cerr );
74                for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
75                        (*i)->print( std::cerr );
76                        (*i)->accept( resolver );
77                } // for
78#endif
79        }
80
81        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
82                TypeEnvironment env;
83                return resolveInVoidContext( expr, indexer, env );
84        }
85
86        namespace {
87                void finishExpr( Expression *expr, const TypeEnvironment &env ) {
88                        expr->set_env( new TypeSubstitution );
89                        env.makeSubstitution( *expr->get_env() );
90                }
91
92                Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
93                        global_renamer.reset();
94                        TypeEnvironment env;
95                        Expression *newExpr = resolveInVoidContext( untyped, indexer, env );
96                        finishExpr( newExpr, env );
97                        return newExpr;
98                }
99
100                Expression *findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
101                        TypeEnvironment env;
102                        AlternativeFinder finder( indexer, env );
103                        finder.find( untyped );
104#if 0
105                        if ( finder.get_alternatives().size() != 1 ) {
106                                std::cout << "untyped expr is ";
107                                untyped->print( std::cout );
108                                std::cout << std::endl << "alternatives are:";
109                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
110                                        i->print( std::cout );
111                                } // for
112                        } // if
113#endif
114                        assert( finder.get_alternatives().size() == 1 );
115                        Alternative &choice = finder.get_alternatives().front();
116                        Expression *newExpr = choice.expr->clone();
117                        finishExpr( newExpr, choice.env );
118                        return newExpr;
119                }
120
121                bool isIntegralType( Type *type ) {
122                        if ( dynamic_cast< EnumInstType * >( type ) ) {
123                                return true;
124                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
125                                return bt->isInteger();
126                        } else {
127                                return false;
128                        } // if
129                }
130
131                Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
132                        TypeEnvironment env;
133                        AlternativeFinder finder( indexer, env );
134                        finder.find( untyped );
135#if 0
136                        if ( finder.get_alternatives().size() != 1 ) {
137                                std::cout << "untyped expr is ";
138                                untyped->print( std::cout );
139                                std::cout << std::endl << "alternatives are:";
140                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
141                                        i->print( std::cout );
142                                } // for
143                        } // if
144#endif
145                        Expression *newExpr = 0;
146                        const TypeEnvironment *newEnv = 0;
147                        for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
148                                if ( i->expr->get_results().size() == 1 && isIntegralType( i->expr->get_results().front() ) ) {
149                                        if ( newExpr ) {
150                                                throw SemanticError( "Too many interpretations for case control expression", untyped );
151                                        } else {
152                                                newExpr = i->expr->clone();
153                                                newEnv = &i->env;
154                                        } // if
155                                } // if
156                        } // for
157                        if ( ! newExpr ) {
158                                throw SemanticError( "No interpretations for case control expression", untyped );
159                        } // if
160                        finishExpr( newExpr, *newEnv );
161                        return newExpr;
162                }
163
164        }
165
166        void Resolver::visit( ObjectDecl *objectDecl ) {
167                Type *new_type = resolveTypeof( objectDecl->get_type(), *this );
168                objectDecl->set_type( new_type );
169                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
170                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
171                // initContext because of a function type can contain object declarations in the return and parameter types. So
172                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
173                // the RHS.
174                Type *temp = initContext;
175                initContext = new_type;
176                SymTab::Indexer::visit( objectDecl );
177                initContext = temp;
178        }
179
180        void Resolver::visit( ArrayType * at ) {
181                if ( at->get_dimension() ) {
182                        BasicType arrayLenType = BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
183                        CastExpr *castExpr = new CastExpr( at->get_dimension(), arrayLenType.clone() );
184                        Expression *newExpr = findSingleExpression( castExpr, *this );
185                        delete at->get_dimension();
186                        at->set_dimension( newExpr );
187                }
188                Visitor::visit( at );
189        }
190
191        void Resolver::visit( TypeDecl *typeDecl ) {
192                if ( typeDecl->get_base() ) {
193                        Type *new_type = resolveTypeof( typeDecl->get_base(), *this );
194                        typeDecl->set_base( new_type );
195                } // if
196                SymTab::Indexer::visit( typeDecl );
197        }
198
199        void Resolver::visit( FunctionDecl *functionDecl ) {
200#if 0
201                std::cout << "resolver visiting functiondecl ";
202                functionDecl->print( std::cout );
203                std::cout << std::endl;
204#endif
205                Type *new_type = resolveTypeof( functionDecl->get_type(), *this );
206                functionDecl->set_type( new_type );
207                std::list< Type * > oldFunctionReturn = functionReturn;
208                functionReturn.clear();
209                for ( std::list< DeclarationWithType * >::const_iterator i = functionDecl->get_functionType()->get_returnVals().begin(); i != functionDecl->get_functionType()->get_returnVals().end(); ++i ) {
210                        functionReturn.push_back( (*i)->get_type() );
211                } // for
212                SymTab::Indexer::visit( functionDecl );
213                functionReturn = oldFunctionReturn;
214        }
215
216        void Resolver::visit( ExprStmt *exprStmt ) {
217                if ( exprStmt->get_expr() ) {
218                        Expression *newExpr = findVoidExpression( exprStmt->get_expr(), *this );
219                        delete exprStmt->get_expr();
220                        exprStmt->set_expr( newExpr );
221                } // if
222        }
223
224        void Resolver::visit( AsmExpr *asmExpr ) {
225                Expression *newExpr = findVoidExpression( asmExpr->get_operand(), *this );
226                delete asmExpr->get_operand();
227                asmExpr->set_operand( newExpr );
228                if ( asmExpr->get_inout() ) {
229                        newExpr = findVoidExpression( asmExpr->get_inout(), *this );
230                        delete asmExpr->get_inout();
231                        asmExpr->set_inout( newExpr );
232                } // if
233        }
234
235        void Resolver::visit( AsmStmt *asmStmt ) {
236                acceptAll( asmStmt->get_input(), *this);
237                acceptAll( asmStmt->get_output(), *this);
238        }
239
240        void Resolver::visit( IfStmt *ifStmt ) {
241                Expression *newExpr = findSingleExpression( ifStmt->get_condition(), *this );
242                delete ifStmt->get_condition();
243                ifStmt->set_condition( newExpr );
244                Visitor::visit( ifStmt );
245        }
246
247        void Resolver::visit( WhileStmt *whileStmt ) {
248                Expression *newExpr = findSingleExpression( whileStmt->get_condition(), *this );
249                delete whileStmt->get_condition();
250                whileStmt->set_condition( newExpr );
251                Visitor::visit( whileStmt );
252        }
253
254        void Resolver::visit( ForStmt *forStmt ) {
255                SymTab::Indexer::visit( forStmt );
256
257                if ( forStmt->get_condition() ) {
258                        Expression * newExpr = findSingleExpression( forStmt->get_condition(), *this );
259                        delete forStmt->get_condition();
260                        forStmt->set_condition( newExpr );
261                } // if
262
263                if ( forStmt->get_increment() ) {
264                        Expression * newExpr = findVoidExpression( forStmt->get_increment(), *this );
265                        delete forStmt->get_increment();
266                        forStmt->set_increment( newExpr );
267                } // if
268        }
269
270        template< typename SwitchClass >
271        void handleSwitchStmt( SwitchClass *switchStmt, SymTab::Indexer &visitor ) {
272                Expression *newExpr;
273                newExpr = findIntegralExpression( switchStmt->get_condition(), visitor );
274                delete switchStmt->get_condition();
275                switchStmt->set_condition( newExpr );
276
277                visitor.Visitor::visit( switchStmt );
278        }
279
280        void Resolver::visit( SwitchStmt *switchStmt ) {
281                handleSwitchStmt( switchStmt, *this );
282        }
283
284        void Resolver::visit( ChooseStmt *switchStmt ) {
285                handleSwitchStmt( switchStmt, *this );
286        }
287
288        void Resolver::visit( CaseStmt *caseStmt ) {
289                Visitor::visit( caseStmt );
290        }
291
292        void Resolver::visit( BranchStmt *branchStmt ) {
293                // must resolve the argument for a computed goto
294                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
295                        if ( Expression * arg = branchStmt->get_computedTarget() ) {
296                                VoidType v = Type::Qualifiers();                // cast to void * for the alternative finder
297                                PointerType pt( Type::Qualifiers(), v.clone() );
298                                CastExpr * castExpr = new CastExpr( arg, pt.clone() );
299                                Expression * newExpr = findSingleExpression( castExpr, *this ); // find best expression
300                                branchStmt->set_target( newExpr );
301                        } // if
302                } // if
303        }
304
305        void Resolver::visit( ReturnStmt *returnStmt ) {
306                if ( returnStmt->get_expr() ) {
307                        CastExpr *castExpr = new CastExpr( returnStmt->get_expr() );
308                        cloneAll( functionReturn, castExpr->get_results() );
309                        Expression *newExpr = findSingleExpression( castExpr, *this );
310                        delete castExpr;
311                        returnStmt->set_expr( newExpr );
312                } // if
313        }
314
315        template< typename T >
316        bool isCharType( T t ) {
317                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
318                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
319                                bt->get_kind() == BasicType::UnsignedChar;
320                }
321                return false;
322        }
323
324        void Resolver::visit( SingleInit *singleInit ) {
325                if ( singleInit->get_value() ) {
326#if 0
327                        if (NameExpr * ne = dynamic_cast<NameExpr*>(singleInit->get_value())) {
328                                string n = ne->get_name();
329                                if (n == "0") {
330                                        initContext = new BasicType(Type::Qualifiers(),
331                                                                                                BasicType::SignedInt);
332                                } else {
333                                        DeclarationWithType * decl = lookupId( n );
334                                        initContext = decl->get_type();
335                                }
336                        } else if (ConstantExpr * e =
337                                           dynamic_cast<ConstantExpr*>(singleInit->get_value())) {
338                                Constant *c = e->get_constant();
339                                initContext = c->get_type();
340                        } else {
341                                assert(0);
342                        }
343#endif
344                        CastExpr *castExpr = new CastExpr( singleInit->get_value(), initContext->clone() );
345                        Expression *newExpr = findSingleExpression( castExpr, *this );
346                        delete castExpr;
347                        singleInit->set_value( newExpr );
348
349                        // check if initializing type is char[]
350                        if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
351                                if ( isCharType( at->get_base() ) ) {
352                                        // check if the resolved type is char *
353                                        if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_results().front() ) ) {
354                                                if ( isCharType( pt->get_base() ) ) {
355                                                        // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
356                                                        CastExpr *ce = dynamic_cast< CastExpr * >( newExpr );
357                                                        singleInit->set_value( ce->get_arg() );
358                                                        ce->set_arg( NULL );
359                                                        delete ce;
360                                                }
361                                        }
362                                }
363                        }
364                } // if
365//      singleInit->get_value()->accept( *this );
366        }
367
368        void Resolver::resolveSingleAggrInit( Declaration * dcl, InitIterator & init, InitIterator & initEnd ) {
369                DeclarationWithType * dt = dynamic_cast< DeclarationWithType * >( dcl );
370                assert( dt );
371                initContext = dt->get_type();
372                try {
373                        if ( init == initEnd ) return; // stop when there are no more initializers
374                        (*init)->accept( *this );
375                        ++init; // made it past an initializer
376                } catch( SemanticError & ) {
377                        // need to delve deeper, if you can
378                        if ( StructInstType * sit = dynamic_cast< StructInstType * >( dt->get_type() ) ) {
379                                resolveAggrInit( sit->get_baseStruct(), init, initEnd );
380                        } else if ( UnionInstType * uit = dynamic_cast< UnionInstType * >( dt->get_type() ) ) {
381                                resolveAggrInit( uit->get_baseUnion(), init, initEnd );
382                        } else {
383                                // member is not an aggregate type, so can't go any deeper
384
385                                // might need to rethink what is being thrown
386                                throw;
387                        } // if
388                }
389        }
390
391        void Resolver::resolveAggrInit( AggregateDecl * aggr, InitIterator & init, InitIterator & initEnd ) {
392                if ( StructDecl * st = dynamic_cast< StructDecl * >( aggr ) ) {
393                        // want to resolve each initializer to the members of the struct,
394                        // but if there are more initializers than members we should stop
395                        list< Declaration * >::iterator it = st->get_members().begin();
396                        for ( ; it != st->get_members().end(); ++it) {
397                                resolveSingleAggrInit( *it, init, initEnd );
398                        }
399                } else if ( UnionDecl * un = dynamic_cast< UnionDecl * >( aggr ) ) {
400                        // only resolve to the first member of a union
401                        resolveSingleAggrInit( *un->get_members().begin(), init, initEnd );
402                } // if
403        }
404
405        void Resolver::visit( ListInit * listInit ) {
406                InitIterator iter = listInit->begin_initializers();
407                InitIterator end = listInit->end_initializers();
408
409                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
410                        // resolve each member to the base type of the array
411                        for ( ; iter != end; ++iter ) {
412                                initContext = at->get_base();
413                                (*iter)->accept( *this );
414                        } // for
415                } else if ( StructInstType * st = dynamic_cast< StructInstType * >( initContext ) ) {
416                        resolveAggrInit( st->get_baseStruct(), iter, end );
417                } else if ( UnionInstType *st = dynamic_cast< UnionInstType * >( initContext ) ) {
418                        resolveAggrInit( st->get_baseUnion(), iter, end );
419                } else {
420                        // basic types are handled here
421                        Visitor::visit( listInit );
422                }
423
424#if 0
425                if ( ArrayType *at = dynamic_cast<ArrayType*>(initContext) ) {
426                        std::list<Initializer *>::iterator iter( listInit->begin_initializers() );
427                        for ( ; iter != listInit->end_initializers(); ++iter ) {
428                                initContext = at->get_base();
429                                (*iter)->accept( *this );
430                        } // for
431                } else if ( StructInstType *st = dynamic_cast<StructInstType*>(initContext) ) {
432                        StructDecl *baseStruct = st->get_baseStruct();
433                        std::list<Declaration *>::iterator iter1( baseStruct->get_members().begin() );
434                        std::list<Initializer *>::iterator iter2( listInit->begin_initializers() );
435                        for ( ; iter1 != baseStruct->get_members().end() && iter2 != listInit->end_initializers(); ++iter2 ) {
436                                if ( (*iter2)->get_designators().empty() ) {
437                                        DeclarationWithType *dt = dynamic_cast<DeclarationWithType *>( *iter1 );
438                                        initContext = dt->get_type();
439                                        (*iter2)->accept( *this );
440                                        ++iter1;
441                                } else {
442                                        StructDecl *st = baseStruct;
443                                        iter1 = st->get_members().begin();
444                                        std::list<Expression *>::iterator iter3( (*iter2)->get_designators().begin() );
445                                        for ( ; iter3 != (*iter2)->get_designators().end(); ++iter3 ) {
446                                                NameExpr *key = dynamic_cast<NameExpr *>( *iter3 );
447                                                assert( key );
448                                                for ( ; iter1 != st->get_members().end(); ++iter1 ) {
449                                                        if ( key->get_name() == (*iter1)->get_name() ) {
450                                                                (*iter1)->print( cout );
451                                                                cout << key->get_name() << endl;
452                                                                ObjectDecl *fred = dynamic_cast<ObjectDecl *>( *iter1 );
453                                                                assert( fred );
454                                                                StructInstType *mary = dynamic_cast<StructInstType*>( fred->get_type() );
455                                                                assert( mary );
456                                                                st = mary->get_baseStruct();
457                                                                iter1 = st->get_members().begin();
458                                                                break;
459                                                        } // if
460                                                }  // for
461                                        } // for
462                                        ObjectDecl *fred = dynamic_cast<ObjectDecl *>( *iter1 );
463                                        assert( fred );
464                                        initContext = fred->get_type();
465                                        (*listInit->begin_initializers())->accept( *this );
466                                } // if
467                        } // for
468                } else if ( UnionInstType *st = dynamic_cast<UnionInstType*>(initContext) ) {
469                        DeclarationWithType *dt = dynamic_cast<DeclarationWithType *>( *st->get_baseUnion()->get_members().begin() );
470                        initContext = dt->get_type();
471                        (*listInit->begin_initializers())->accept( *this );
472                } // if
473#endif
474        }
475
476        // ConstructorInit - fall back on C-style initializer
477        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
478                // could not find valid constructor, or found an intrinsic constructor
479                // fall back on C-style initializer
480                delete ctorInit->get_ctor();
481                ctorInit->set_ctor( NULL );
482                maybeAccept( ctorInit->get_init(), *this );
483        }
484
485        void Resolver::visit( ConstructorInit *ctorInit ) {
486                TypeEnvironment env;
487                try {
488                        maybeAccept( ctorInit->get_ctor(), *this );
489                        maybeAccept( ctorInit->get_dtor(), *this );
490                } catch ( SemanticError ) {
491                        // no alternatives for the constructor initializer - fallback on C-style initializer
492                        // xxx- not sure if this makes a ton of sense - should maybe never be able to have this situation?
493                        fallbackInit( ctorInit );
494                        return;
495                }
496
497                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * > ( ctorInit->get_ctor() ) ) {
498                        ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( exprStmt->get_expr() );
499                        assert( appExpr );
500                        VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() );
501                        assert( function );
502                        if ( LinkageSpec::isOverridable( function->get_var()->get_linkage() ) ) {
503                                // if the constructor that was found is intrinsic or autogenerated, reset to C-style
504                                // initializer so that code generation is easy to handle
505                                fallbackInit( ctorInit );
506                                return;
507                        }
508                }
509                // found a constructor - can get rid of C-style initializer
510                delete ctorInit->get_init();
511                ctorInit->set_init( NULL );
512        }
513} // namespace ResolvExpr
514
515// Local Variables: //
516// tab-width: 4 //
517// mode: c++ //
518// compile-command: "make install" //
519// End: //
Note: See TracBrowser for help on using the repository browser.