source: src/ResolvExpr/Resolver.cc @ 435e75f

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

fix dropped environment

  • Property mode set to 100644
File size: 18.3 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 : Peter A. Buhr
12// Last Modified On : Thu Mar 23 17:23:14 2017
13// Update Count     : 211
14//
15
16#include <iostream>
17
18#include "Alternative.h"
19#include "AlternativeFinder.h"
20#include "CurrentObject.h"
21#include "RenameVars.h"
22#include "Resolver.h"
23#include "ResolveTypeof.h"
24#include "typeops.h"
25
26#include "SynTree/Expression.h"
27#include "SynTree/Initializer.h"
28#include "SynTree/Statement.h"
29#include "SynTree/Type.h"
30
31#include "SymTab/Autogen.h"
32#include "SymTab/Indexer.h"
33
34#include "Common/utility.h"
35
36#include "InitTweak/InitTweak.h"
37
38using namespace std;
39
40namespace ResolvExpr {
41        class Resolver final : public SymTab::Indexer {
42          public:
43                Resolver() : SymTab::Indexer( false ) {}
44                Resolver( const SymTab:: Indexer & other ) : SymTab::Indexer( other ) {
45                        if ( const Resolver * res = dynamic_cast< const Resolver * >( &other ) ) {
46                                functionReturn = res->functionReturn;
47                                currentObject = res->currentObject;
48                                inEnumDecl = res->inEnumDecl;
49                        }
50                }
51
52                typedef SymTab::Indexer Parent;
53                using Parent::visit;
54                virtual void visit( FunctionDecl *functionDecl ) override;
55                virtual void visit( ObjectDecl *functionDecl ) override;
56                virtual void visit( TypeDecl *typeDecl ) override;
57                virtual void visit( EnumDecl * enumDecl ) override;
58
59                virtual void visit( ArrayType * at ) override;
60                virtual void visit( PointerType * at ) override;
61
62                virtual void visit( ExprStmt *exprStmt ) override;
63                virtual void visit( AsmExpr *asmExpr ) override;
64                virtual void visit( AsmStmt *asmStmt ) override;
65                virtual void visit( IfStmt *ifStmt ) override;
66                virtual void visit( WhileStmt *whileStmt ) override;
67                virtual void visit( ForStmt *forStmt ) override;
68                virtual void visit( SwitchStmt *switchStmt ) override;
69                virtual void visit( CaseStmt *caseStmt ) override;
70                virtual void visit( BranchStmt *branchStmt ) override;
71                virtual void visit( ReturnStmt *returnStmt ) override;
72
73                virtual void visit( SingleInit *singleInit ) override;
74                virtual void visit( ListInit *listInit ) override;
75                virtual void visit( ConstructorInit *ctorInit ) override;
76          private:
77        typedef std::list< Initializer * >::iterator InitIterator;
78
79                template< typename PtrType >
80                void handlePtrType( PtrType * type );
81
82          void resolveAggrInit( ReferenceToType *, InitIterator &, InitIterator & );
83          void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator &, TypeSubstitution sub );
84          void fallbackInit( ConstructorInit * ctorInit );
85
86                Type * functionReturn = nullptr;
87                CurrentObject currentObject = nullptr;
88                bool inEnumDecl = false;
89        };
90
91        void resolve( std::list< Declaration * > translationUnit ) {
92                Resolver resolver;
93                acceptAll( translationUnit, resolver );
94        }
95
96        Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
97                TypeEnvironment env;
98                return resolveInVoidContext( expr, indexer, env );
99        }
100
101
102        namespace {
103                void finishExpr( Expression *expr, const TypeEnvironment &env ) {
104                        expr->set_env( new TypeSubstitution );
105                        env.makeSubstitution( *expr->get_env() );
106                }
107        } // namespace
108
109        Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
110                global_renamer.reset();
111                TypeEnvironment env;
112                Expression *newExpr = resolveInVoidContext( untyped, indexer, env );
113                finishExpr( newExpr, env );
114                return newExpr;
115        }
116
117        namespace {
118                Expression *findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
119                        TypeEnvironment env;
120                        AlternativeFinder finder( indexer, env );
121                        finder.find( untyped );
122#if 0
123                        if ( finder.get_alternatives().size() != 1 ) {
124                                std::cout << "untyped expr is ";
125                                untyped->print( std::cout );
126                                std::cout << std::endl << "alternatives are:";
127                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
128                                        i->print( std::cout );
129                                } // for
130                        } // if
131#endif
132                        assertf( finder.get_alternatives().size() == 1, "findSingleExpression: must have exactly one alternative at the end." );
133                        Alternative &choice = finder.get_alternatives().front();
134                        Expression *newExpr = choice.expr->clone();
135                        finishExpr( newExpr, choice.env );
136                        return newExpr;
137                }
138
139                bool isIntegralType( Type *type ) {
140                        if ( dynamic_cast< EnumInstType * >( type ) ) {
141                                return true;
142                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
143                                return bt->isInteger();
144                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
145                                return true;
146                        } else {
147                                return false;
148                        } // if
149                }
150
151                Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) {
152                        TypeEnvironment env;
153                        AlternativeFinder finder( indexer, env );
154                        finder.find( untyped );
155#if 0
156                        if ( finder.get_alternatives().size() != 1 ) {
157                                std::cout << "untyped expr is ";
158                                untyped->print( std::cout );
159                                std::cout << std::endl << "alternatives are:";
160                                for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
161                                        i->print( std::cout );
162                                } // for
163                        } // if
164#endif
165                        Expression *newExpr = 0;
166                        const TypeEnvironment *newEnv = 0;
167                        for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) {
168                                if ( i->expr->get_result()->size() == 1 && isIntegralType( i->expr->get_result() ) ) {
169                                        if ( newExpr ) {
170                                                throw SemanticError( "Too many interpretations for case control expression", untyped );
171                                        } else {
172                                                newExpr = i->expr->clone();
173                                                newEnv = &i->env;
174                                        } // if
175                                } // if
176                        } // for
177                        if ( ! newExpr ) {
178                                throw SemanticError( "No interpretations for case control expression", untyped );
179                        } // if
180                        finishExpr( newExpr, *newEnv );
181                        return newExpr;
182                }
183
184        }
185
186        void Resolver::visit( ObjectDecl *objectDecl ) {
187                Type *new_type = resolveTypeof( objectDecl->get_type(), *this );
188                objectDecl->set_type( new_type );
189                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable
190                // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes
191                // initContext because of a function type can contain object declarations in the return and parameter types. So
192                // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting
193                // the RHS.
194                ValueGuard<CurrentObject> temp( currentObject );
195                currentObject = CurrentObject( objectDecl->get_type() );
196                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
197                        // enumerator initializers should not use the enum type to initialize, since
198                        // the enum type is still incomplete at this point. Use signed int instead.
199                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
200                }
201                Parent::visit( objectDecl );
202                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
203                        // delete newly created signed int type
204                        // delete currentObject.getType();
205                }
206        }
207
208        template< typename PtrType >
209        void Resolver::handlePtrType( PtrType * type ) {
210                if ( type->get_dimension() ) {
211                        CastExpr *castExpr = new CastExpr( type->get_dimension(), SymTab::SizeType->clone() );
212                        Expression *newExpr = findSingleExpression( castExpr, *this );
213                        delete type->get_dimension();
214                        type->set_dimension( newExpr );
215                }
216        }
217
218        void Resolver::visit( ArrayType * at ) {
219                handlePtrType( at );
220                Parent::visit( at );
221        }
222
223        void Resolver::visit( PointerType * pt ) {
224                handlePtrType( pt );
225                Parent::visit( pt );
226        }
227
228        void Resolver::visit( TypeDecl *typeDecl ) {
229                if ( typeDecl->get_base() ) {
230                        Type *new_type = resolveTypeof( typeDecl->get_base(), *this );
231                        typeDecl->set_base( new_type );
232                } // if
233                Parent::visit( typeDecl );
234        }
235
236        void Resolver::visit( FunctionDecl *functionDecl ) {
237#if 0
238                std::cout << "resolver visiting functiondecl ";
239                functionDecl->print( std::cout );
240                std::cout << std::endl;
241#endif
242                Type *new_type = resolveTypeof( functionDecl->get_type(), *this );
243                functionDecl->set_type( new_type );
244                ValueGuard< Type * > oldFunctionReturn( functionReturn );
245                functionReturn = ResolvExpr::extractResultType( functionDecl->get_functionType() );
246                Parent::visit( functionDecl );
247
248                // default value expressions have an environment which shouldn't be there and trips up later passes.
249                // xxx - it might be necessary to somehow keep the information from this environment, but I can't currently
250                // see how it's useful.
251                for ( Declaration * d : functionDecl->get_functionType()->get_parameters() ) {
252                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
253                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->get_init() ) ) {
254                                        delete init->get_value()->get_env();
255                                        init->get_value()->set_env( nullptr );
256                                }
257                        }
258                }
259        }
260
261        void Resolver::visit( EnumDecl * enumDecl ) {
262                // in case we decide to allow nested enums
263                ValueGuard< bool > oldInEnumDecl( inEnumDecl );
264                inEnumDecl = true;
265                Parent::visit( enumDecl );
266        }
267
268        void Resolver::visit( ExprStmt *exprStmt ) {
269                assertf( exprStmt->get_expr(), "ExprStmt has null Expression in resolver" );
270                Expression *newExpr = findVoidExpression( exprStmt->get_expr(), *this );
271                delete exprStmt->get_expr();
272                exprStmt->set_expr( newExpr );
273        }
274
275        void Resolver::visit( AsmExpr *asmExpr ) {
276                Expression *newExpr = findVoidExpression( asmExpr->get_operand(), *this );
277                delete asmExpr->get_operand();
278                asmExpr->set_operand( newExpr );
279                if ( asmExpr->get_inout() ) {
280                        newExpr = findVoidExpression( asmExpr->get_inout(), *this );
281                        delete asmExpr->get_inout();
282                        asmExpr->set_inout( newExpr );
283                } // if
284        }
285
286        void Resolver::visit( AsmStmt *asmStmt ) {
287                acceptAll( asmStmt->get_input(), *this);
288                acceptAll( asmStmt->get_output(), *this);
289        }
290
291        void Resolver::visit( IfStmt *ifStmt ) {
292                Expression *newExpr = findSingleExpression( ifStmt->get_condition(), *this );
293                delete ifStmt->get_condition();
294                ifStmt->set_condition( newExpr );
295                Parent::visit( ifStmt );
296        }
297
298        void Resolver::visit( WhileStmt *whileStmt ) {
299                Expression *newExpr = findSingleExpression( whileStmt->get_condition(), *this );
300                delete whileStmt->get_condition();
301                whileStmt->set_condition( newExpr );
302                Parent::visit( whileStmt );
303        }
304
305        void Resolver::visit( ForStmt *forStmt ) {
306                Parent::visit( forStmt );
307
308                if ( forStmt->get_condition() ) {
309                        Expression * newExpr = findSingleExpression( forStmt->get_condition(), *this );
310                        delete forStmt->get_condition();
311                        forStmt->set_condition( newExpr );
312                } // if
313
314                if ( forStmt->get_increment() ) {
315                        Expression * newExpr = findVoidExpression( forStmt->get_increment(), *this );
316                        delete forStmt->get_increment();
317                        forStmt->set_increment( newExpr );
318                } // if
319        }
320
321        void Resolver::visit( SwitchStmt *switchStmt ) {
322                ValueGuard< CurrentObject > oldCurrentObject( currentObject );
323                Expression *newExpr;
324                newExpr = findIntegralExpression( switchStmt->get_condition(), *this );
325                delete switchStmt->get_condition();
326                switchStmt->set_condition( newExpr );
327
328                currentObject = CurrentObject( newExpr->get_result() );
329                Parent::visit( switchStmt );
330        }
331
332        void Resolver::visit( CaseStmt *caseStmt ) {
333                if ( caseStmt->get_condition() ) {
334                        std::list< InitAlternative > initAlts = currentObject.getOptions();
335                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
336                        CastExpr * castExpr = new CastExpr( caseStmt->get_condition(), initAlts.front().type->clone() );
337                        Expression * newExpr = findSingleExpression( castExpr, *this );
338                        castExpr = safe_dynamic_cast< CastExpr * >( newExpr );
339                        caseStmt->set_condition( castExpr->get_arg() );
340                        castExpr->set_arg( nullptr );
341                        delete castExpr;
342                }
343                Parent::visit( caseStmt );
344        }
345
346        void Resolver::visit( BranchStmt *branchStmt ) {
347                // must resolve the argument for a computed goto
348                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
349                        if ( Expression * arg = branchStmt->get_computedTarget() ) {
350                                VoidType v = Type::Qualifiers();                // cast to void * for the alternative finder
351                                PointerType pt( Type::Qualifiers(), v.clone() );
352                                CastExpr * castExpr = new CastExpr( arg, pt.clone() );
353                                Expression * newExpr = findSingleExpression( castExpr, *this ); // find best expression
354                                branchStmt->set_target( newExpr );
355                        } // if
356                } // if
357        }
358
359        void Resolver::visit( ReturnStmt *returnStmt ) {
360                if ( returnStmt->get_expr() ) {
361                        CastExpr *castExpr = new CastExpr( returnStmt->get_expr(), functionReturn->clone() );
362                        Expression *newExpr = findSingleExpression( castExpr, *this );
363                        delete castExpr;
364                        returnStmt->set_expr( newExpr );
365                } // if
366        }
367
368        template< typename T >
369        bool isCharType( T t ) {
370                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
371                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
372                                bt->get_kind() == BasicType::UnsignedChar;
373                }
374                return false;
375        }
376
377        void Resolver::visit( SingleInit *singleInit ) {
378                // resolve initialization using the possibilities as determined by the currentObject cursor
379                UntypedInitExpr * untyped = new UntypedInitExpr( singleInit->get_value(), currentObject.getOptions() );
380                Expression * newExpr = findSingleExpression( untyped, *this );
381                InitExpr * initExpr = safe_dynamic_cast< InitExpr * >( newExpr );
382
383                // move cursor to the object that is actually initialized
384                currentObject.setNext( initExpr->get_designation() );
385
386                // discard InitExpr wrapper and retain relevant pieces
387                newExpr = initExpr->get_expr();
388                newExpr->set_env( initExpr->get_env() );
389                initExpr->set_expr( nullptr );
390                initExpr->set_env( nullptr );
391                delete initExpr;
392
393                // get the actual object's type (may not exactly match what comes back from the resolver due to conversions)
394                Type * initContext = currentObject.getCurrentType();
395
396                // check if actual object's type is char[]
397                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
398                        if ( isCharType( at->get_base() ) ) {
399                                // check if the resolved type is char *
400                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
401                                        if ( isCharType( pt->get_base() ) ) {
402                                                // strip cast if we're initializing a char[] with a char *, e.g.  char x[] = "hello";
403                                                CastExpr *ce = safe_dynamic_cast< CastExpr * >( newExpr );
404                                                newExpr = ce->get_arg();
405                                                ce->set_arg( nullptr );
406                                                delete ce;
407                                        }
408                                }
409                        }
410                }
411
412                // set initializer expr to resolved express
413                singleInit->set_value( newExpr );
414
415                // move cursor to next object in preparation for next initializer
416                currentObject.increment();
417        }
418
419        void Resolver::visit( ListInit * listInit ) {
420                // move cursor into brace-enclosed initializer-list
421                currentObject.enterListInit();
422                // xxx - fix this so that the list isn't copied, iterator should be used to change current element
423                std::list<Designation *> newDesignations;
424                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
425                        // iterate designations and initializers in pairs, moving the cursor to the current designated object and resolving
426                        // the initializer against that object.
427                        Designation * des = std::get<0>(p);
428                        Initializer * init = std::get<1>(p);
429                        newDesignations.push_back( currentObject.findNext( des ) );
430                        init->accept( *this );
431                }
432                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
433                listInit->get_designations() = newDesignations; // xxx - memory management
434                currentObject.exitListInit();
435
436                // xxx - this part has not be folded into CurrentObject yet
437                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
438                //      Type * base = tt->get_baseType()->get_base();
439                //      if ( base ) {
440                //              // know the implementation type, so try using that as the initContext
441                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
442                //              currentObject = &tmpObj;
443                //              visit( listInit );
444                //      } else {
445                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
446                //              Parent::visit( listInit );
447                //      }
448                // } else {
449        }
450
451        // ConstructorInit - fall back on C-style initializer
452        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
453                // could not find valid constructor, or found an intrinsic constructor
454                // fall back on C-style initializer
455                delete ctorInit->get_ctor();
456                ctorInit->set_ctor( NULL );
457                delete ctorInit->get_dtor();
458                ctorInit->set_dtor( NULL );
459                maybeAccept( ctorInit->get_init(), *this );
460        }
461
462        // needs to be callable from outside the resolver, so this is a standalone function
463        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
464                assert( ctorInit );
465                Resolver resolver( indexer );
466                ctorInit->accept( resolver );
467        }
468
469        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
470                assert( stmtExpr );
471                Resolver resolver( indexer );
472                stmtExpr->accept( resolver );
473        }
474
475        void Resolver::visit( ConstructorInit *ctorInit ) {
476                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
477                maybeAccept( ctorInit->get_ctor(), *this );
478                maybeAccept( ctorInit->get_dtor(), *this );
479
480                // found a constructor - can get rid of C-style initializer
481                delete ctorInit->get_init();
482                ctorInit->set_init( NULL );
483
484                // intrinsic single parameter constructors and destructors do nothing. Since this was
485                // implicitly generated, there's no way for it to have side effects, so get rid of it
486                // to clean up generated code.
487                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) {
488                        delete ctorInit->get_ctor();
489                        ctorInit->set_ctor( NULL );
490                }
491
492                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) {
493                        delete ctorInit->get_dtor();
494                        ctorInit->set_dtor( NULL );
495                }
496
497                // xxx - todo -- what about arrays?
498                // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
499                //      // can reduce the constructor down to a SingleInit using the
500                //      // second argument from the ctor call, since
501                //      delete ctorInit->get_ctor();
502                //      ctorInit->set_ctor( NULL );
503
504                //      Expression * arg =
505                //      ctorInit->set_init( new SingleInit( arg ) );
506                // }
507        }
508} // namespace ResolvExpr
509
510// Local Variables: //
511// tab-width: 4 //
512// mode: c++ //
513// compile-command: "make install" //
514// End: //
Note: See TracBrowser for help on using the repository browser.