// // Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo // // The contents of this file are covered under the licence agreement in the // file "LICENCE" distributed with Cforall. // // Resolver.cc -- // // Author : Richard C. Bilson // Created On : Sun May 17 12:17:01 2015 // Last Modified By : Peter A. Buhr // Last Modified On : Tue Jul 12 17:45:42 2016 // Update Count : 204 // #include "Resolver.h" #include "AlternativeFinder.h" #include "Alternative.h" #include "RenameVars.h" #include "ResolveTypeof.h" #include "typeops.h" #include "SynTree/Statement.h" #include "SynTree/Type.h" #include "SynTree/Expression.h" #include "SynTree/Initializer.h" #include "SymTab/Indexer.h" #include "SymTab/Autogen.h" #include "Common/utility.h" #include "InitTweak/InitTweak.h" #include using namespace std; namespace ResolvExpr { class Resolver final : public SymTab::Indexer { public: Resolver() : SymTab::Indexer( false ) {} Resolver( const SymTab:: Indexer & other ) : SymTab::Indexer( other ) { if ( const Resolver * res = dynamic_cast< const Resolver * >( &other ) ) { functionReturn = res->functionReturn; initContext = res->initContext; inEnumDecl = res->inEnumDecl; } } typedef SymTab::Indexer Parent; using Parent::visit; virtual void visit( FunctionDecl *functionDecl ) override; virtual void visit( ObjectDecl *functionDecl ) override; virtual void visit( TypeDecl *typeDecl ) override; virtual void visit( EnumDecl * enumDecl ) override; virtual void visit( ArrayType * at ) override; virtual void visit( PointerType * at ) override; virtual void visit( ExprStmt *exprStmt ) override; virtual void visit( AsmExpr *asmExpr ) override; virtual void visit( AsmStmt *asmStmt ) override; virtual void visit( IfStmt *ifStmt ) override; virtual void visit( WhileStmt *whileStmt ) override; virtual void visit( ForStmt *forStmt ) override; virtual void visit( SwitchStmt *switchStmt ) override; virtual void visit( CaseStmt *caseStmt ) override; virtual void visit( BranchStmt *branchStmt ) override; virtual void visit( ReturnStmt *returnStmt ) override; virtual void visit( SingleInit *singleInit ) override; virtual void visit( ListInit *listInit ) override; virtual void visit( ConstructorInit *ctorInit ) override; private: typedef std::list< Initializer * >::iterator InitIterator; template< typename PtrType > void handlePtrType( PtrType * type ); void resolveAggrInit( ReferenceToType *, InitIterator &, InitIterator & ); void resolveSingleAggrInit( Declaration *, InitIterator &, InitIterator &, TypeSubstitution sub ); void fallbackInit( ConstructorInit * ctorInit ); Type * functionReturn = nullptr; Type *initContext = nullptr; bool inEnumDecl = false; }; void resolve( std::list< Declaration * > translationUnit ) { Resolver resolver; acceptAll( translationUnit, resolver ); } Expression *resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) { TypeEnvironment env; return resolveInVoidContext( expr, indexer, env ); } namespace { void finishExpr( Expression *expr, const TypeEnvironment &env ) { expr->set_env( new TypeSubstitution ); env.makeSubstitution( *expr->get_env() ); } } // namespace Expression *findVoidExpression( Expression *untyped, const SymTab::Indexer &indexer ) { global_renamer.reset(); TypeEnvironment env; Expression *newExpr = resolveInVoidContext( untyped, indexer, env ); finishExpr( newExpr, env ); return newExpr; } namespace { Expression *findSingleExpression( Expression *untyped, const SymTab::Indexer &indexer ) { TypeEnvironment env; AlternativeFinder finder( indexer, env ); finder.find( untyped ); #if 0 if ( finder.get_alternatives().size() != 1 ) { std::cout << "untyped expr is "; untyped->print( std::cout ); std::cout << std::endl << "alternatives are:"; for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) { i->print( std::cout ); } // for } // if #endif assert( finder.get_alternatives().size() == 1 ); Alternative &choice = finder.get_alternatives().front(); Expression *newExpr = choice.expr->clone(); finishExpr( newExpr, choice.env ); return newExpr; } bool isIntegralType( Type *type ) { if ( dynamic_cast< EnumInstType * >( type ) ) { return true; } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) { return bt->isInteger(); } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) { return true; } else { return false; } // if } Expression *findIntegralExpression( Expression *untyped, const SymTab::Indexer &indexer ) { TypeEnvironment env; AlternativeFinder finder( indexer, env ); finder.find( untyped ); #if 0 if ( finder.get_alternatives().size() != 1 ) { std::cout << "untyped expr is "; untyped->print( std::cout ); std::cout << std::endl << "alternatives are:"; for ( std::list< Alternative >::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) { i->print( std::cout ); } // for } // if #endif Expression *newExpr = 0; const TypeEnvironment *newEnv = 0; for ( AltList::const_iterator i = finder.get_alternatives().begin(); i != finder.get_alternatives().end(); ++i ) { if ( i->expr->get_result()->size() == 1 && isIntegralType( i->expr->get_result() ) ) { if ( newExpr ) { throw SemanticError( "Too many interpretations for case control expression", untyped ); } else { newExpr = i->expr->clone(); newEnv = &i->env; } // if } // if } // for if ( ! newExpr ) { throw SemanticError( "No interpretations for case control expression", untyped ); } // if finishExpr( newExpr, *newEnv ); return newExpr; } } void Resolver::visit( ObjectDecl *objectDecl ) { Type *new_type = resolveTypeof( objectDecl->get_type(), *this ); objectDecl->set_type( new_type ); // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that class-variable // initContext is changed multiple time because the LHS is analysed twice. The second analysis changes // initContext because of a function type can contain object declarations in the return and parameter types. So // each value of initContext is retained, so the type on the first analysis is preserved and used for selecting // the RHS. Type *temp = initContext; initContext = new_type; if ( inEnumDecl && dynamic_cast< EnumInstType * >( initContext ) ) { // enumerator initializers should not use the enum type to initialize, since // the enum type is still incomplete at this point. Use signed int instead. initContext = new BasicType( Type::Qualifiers(), BasicType::SignedInt ); } Parent::visit( objectDecl ); if ( inEnumDecl && dynamic_cast< EnumInstType * >( initContext ) ) { // delete newly created signed int type delete initContext; } initContext = temp; } template< typename PtrType > void Resolver::handlePtrType( PtrType * type ) { if ( type->get_dimension() ) { CastExpr *castExpr = new CastExpr( type->get_dimension(), SymTab::SizeType->clone() ); Expression *newExpr = findSingleExpression( castExpr, *this ); delete type->get_dimension(); type->set_dimension( newExpr ); } } void Resolver::visit( ArrayType * at ) { handlePtrType( at ); Parent::visit( at ); } void Resolver::visit( PointerType * pt ) { handlePtrType( pt ); Parent::visit( pt ); } void Resolver::visit( TypeDecl *typeDecl ) { if ( typeDecl->get_base() ) { Type *new_type = resolveTypeof( typeDecl->get_base(), *this ); typeDecl->set_base( new_type ); } // if Parent::visit( typeDecl ); } void Resolver::visit( FunctionDecl *functionDecl ) { #if 0 std::cout << "resolver visiting functiondecl "; functionDecl->print( std::cout ); std::cout << std::endl; #endif Type *new_type = resolveTypeof( functionDecl->get_type(), *this ); functionDecl->set_type( new_type ); ValueGuard< Type * > oldFunctionReturn( functionReturn ); functionReturn = ResolvExpr::extractResultType( functionDecl->get_functionType() ); Parent::visit( functionDecl ); } void Resolver::visit( EnumDecl * enumDecl ) { // in case we decide to allow nested enums ValueGuard< bool > oldInEnumDecl( inEnumDecl ); inEnumDecl = true; Parent::visit( enumDecl ); } void Resolver::visit( ExprStmt *exprStmt ) { assertf( exprStmt->get_expr(), "ExprStmt has null Expression in resolver" ); Expression *newExpr = findVoidExpression( exprStmt->get_expr(), *this ); delete exprStmt->get_expr(); exprStmt->set_expr( newExpr ); } void Resolver::visit( AsmExpr *asmExpr ) { Expression *newExpr = findVoidExpression( asmExpr->get_operand(), *this ); delete asmExpr->get_operand(); asmExpr->set_operand( newExpr ); if ( asmExpr->get_inout() ) { newExpr = findVoidExpression( asmExpr->get_inout(), *this ); delete asmExpr->get_inout(); asmExpr->set_inout( newExpr ); } // if } void Resolver::visit( AsmStmt *asmStmt ) { acceptAll( asmStmt->get_input(), *this); acceptAll( asmStmt->get_output(), *this); } void Resolver::visit( IfStmt *ifStmt ) { Expression *newExpr = findSingleExpression( ifStmt->get_condition(), *this ); delete ifStmt->get_condition(); ifStmt->set_condition( newExpr ); Parent::visit( ifStmt ); } void Resolver::visit( WhileStmt *whileStmt ) { Expression *newExpr = findSingleExpression( whileStmt->get_condition(), *this ); delete whileStmt->get_condition(); whileStmt->set_condition( newExpr ); Parent::visit( whileStmt ); } void Resolver::visit( ForStmt *forStmt ) { Parent::visit( forStmt ); if ( forStmt->get_condition() ) { Expression * newExpr = findSingleExpression( forStmt->get_condition(), *this ); delete forStmt->get_condition(); forStmt->set_condition( newExpr ); } // if if ( forStmt->get_increment() ) { Expression * newExpr = findVoidExpression( forStmt->get_increment(), *this ); delete forStmt->get_increment(); forStmt->set_increment( newExpr ); } // if } void Resolver::visit( SwitchStmt *switchStmt ) { ValueGuard< Type * > oldInitContext( initContext ); Expression *newExpr; newExpr = findIntegralExpression( switchStmt->get_condition(), *this ); delete switchStmt->get_condition(); switchStmt->set_condition( newExpr ); initContext = newExpr->get_result(); Parent::visit( switchStmt ); } void Resolver::visit( CaseStmt *caseStmt ) { if ( caseStmt->get_condition() ) { assert( initContext ); CastExpr * castExpr = new CastExpr( caseStmt->get_condition(), initContext->clone() ); Expression * newExpr = findSingleExpression( castExpr, *this ); castExpr = safe_dynamic_cast< CastExpr * >( newExpr ); caseStmt->set_condition( castExpr->get_arg() ); castExpr->set_arg( nullptr ); delete castExpr; } Parent::visit( caseStmt ); } void Resolver::visit( BranchStmt *branchStmt ) { // must resolve the argument for a computed goto if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement if ( Expression * arg = branchStmt->get_computedTarget() ) { VoidType v = Type::Qualifiers(); // cast to void * for the alternative finder PointerType pt( Type::Qualifiers(), v.clone() ); CastExpr * castExpr = new CastExpr( arg, pt.clone() ); Expression * newExpr = findSingleExpression( castExpr, *this ); // find best expression branchStmt->set_target( newExpr ); } // if } // if } void Resolver::visit( ReturnStmt *returnStmt ) { if ( returnStmt->get_expr() ) { CastExpr *castExpr = new CastExpr( returnStmt->get_expr(), functionReturn->clone() ); Expression *newExpr = findSingleExpression( castExpr, *this ); delete castExpr; returnStmt->set_expr( newExpr ); } // if } template< typename T > bool isCharType( T t ) { if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) { return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar || bt->get_kind() == BasicType::UnsignedChar; } return false; } void Resolver::visit( SingleInit *singleInit ) { if ( singleInit->get_value() ) { #if 0 if (NameExpr * ne = dynamic_cast(singleInit->get_value())) { string n = ne->get_name(); if (n == "0") { initContext = new BasicType(Type::Qualifiers(), BasicType::SignedInt); } else { DeclarationWithType * decl = lookupId( n ); initContext = decl->get_type(); } } else if (ConstantExpr * e = dynamic_cast(singleInit->get_value())) { Constant *c = e->get_constant(); initContext = c->get_type(); } else { assert(0); } #endif CastExpr *castExpr = new CastExpr( singleInit->get_value(), initContext->clone() ); Expression *newExpr = findSingleExpression( castExpr, *this ); delete castExpr; singleInit->set_value( newExpr ); // check if initializing type is char[] if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) { if ( isCharType( at->get_base() ) ) { // check if the resolved type is char * if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) { if ( isCharType( pt->get_base() ) ) { // strip cast if we're initializing a char[] with a char *, e.g. char x[] = "hello"; CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ); singleInit->set_value( ce->get_arg() ); ce->set_arg( NULL ); delete ce; } } } } } // if // singleInit->get_value()->accept( *this ); } template< typename AggrInst > TypeSubstitution makeGenericSubstitutuion( AggrInst * inst ) { assert( inst ); assert( inst->get_baseParameters() ); std::list< TypeDecl * > baseParams = *inst->get_baseParameters(); std::list< Expression * > typeSubs = inst->get_parameters(); TypeSubstitution subs( baseParams.begin(), baseParams.end(), typeSubs.begin() ); return subs; } ReferenceToType * isStructOrUnion( Type * type ) { if ( StructInstType * sit = dynamic_cast< StructInstType * >( type ) ) { return sit; } else if ( UnionInstType * uit = dynamic_cast< UnionInstType * >( type ) ) { return uit; } return nullptr; } void Resolver::resolveSingleAggrInit( Declaration * dcl, InitIterator & init, InitIterator & initEnd, TypeSubstitution sub ) { DeclarationWithType * dt = dynamic_cast< DeclarationWithType * >( dcl ); assert( dt ); // need to substitute for generic types, so that casts are to concrete types initContext = dt->get_type()->clone(); sub.apply( initContext ); try { if ( init == initEnd ) return; // stop when there are no more initializers (*init)->accept( *this ); ++init; // made it past an initializer } catch( SemanticError & ) { // need to delve deeper, if you can if ( ReferenceToType * type = isStructOrUnion( initContext ) ) { resolveAggrInit( type, init, initEnd ); } else { // member is not an aggregate type, so can't go any deeper // might need to rethink what is being thrown throw; } // if } } void Resolver::resolveAggrInit( ReferenceToType * inst, InitIterator & init, InitIterator & initEnd ) { if ( StructInstType * sit = dynamic_cast< StructInstType * >( inst ) ) { TypeSubstitution sub = makeGenericSubstitutuion( sit ); StructDecl * st = sit->get_baseStruct(); if(st->get_members().empty()) return; // want to resolve each initializer to the members of the struct, // but if there are more initializers than members we should stop list< Declaration * >::iterator it = st->get_members().begin(); for ( ; it != st->get_members().end(); ++it) { resolveSingleAggrInit( *it, init, initEnd, sub ); } } else if ( UnionInstType * uit = dynamic_cast< UnionInstType * >( inst ) ) { TypeSubstitution sub = makeGenericSubstitutuion( uit ); UnionDecl * un = uit->get_baseUnion(); if(un->get_members().empty()) return; // only resolve to the first member of a union resolveSingleAggrInit( *un->get_members().begin(), init, initEnd, sub ); } // if } void Resolver::visit( ListInit * listInit ) { InitIterator iter = listInit->begin(); InitIterator end = listInit->end(); if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) { // resolve each member to the base type of the array for ( ; iter != end; ++iter ) { initContext = at->get_base(); (*iter)->accept( *this ); } // for } else if ( TupleType * tt = dynamic_cast< TupleType * > ( initContext ) ) { for ( Type * t : *tt ) { if ( iter == end ) break; initContext = t; (*iter++)->accept( *this ); } } else if ( ReferenceToType * type = isStructOrUnion( initContext ) ) { resolveAggrInit( type, iter, end ); } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) { Type * base = tt->get_baseType()->get_base(); if ( base ) { // know the implementation type, so try using that as the initContext initContext = base; visit( listInit ); } else { // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context Parent::visit( listInit ); } } else { assert( dynamic_cast< BasicType * >( initContext ) || dynamic_cast< PointerType * >( initContext ) || dynamic_cast< ZeroType * >( initContext ) || dynamic_cast< OneType * >( initContext ) || dynamic_cast < EnumInstType * > ( initContext ) ); // basic types are handled here Parent::visit( listInit ); } #if 0 if ( ArrayType *at = dynamic_cast(initContext) ) { std::list::iterator iter( listInit->begin_initializers() ); for ( ; iter != listInit->end_initializers(); ++iter ) { initContext = at->get_base(); (*iter)->accept( *this ); } // for } else if ( StructInstType *st = dynamic_cast(initContext) ) { StructDecl *baseStruct = st->get_baseStruct(); std::list::iterator iter1( baseStruct->get_members().begin() ); std::list::iterator iter2( listInit->begin_initializers() ); for ( ; iter1 != baseStruct->get_members().end() && iter2 != listInit->end_initializers(); ++iter2 ) { if ( (*iter2)->get_designators().empty() ) { DeclarationWithType *dt = dynamic_cast( *iter1 ); initContext = dt->get_type(); (*iter2)->accept( *this ); ++iter1; } else { StructDecl *st = baseStruct; iter1 = st->get_members().begin(); std::list::iterator iter3( (*iter2)->get_designators().begin() ); for ( ; iter3 != (*iter2)->get_designators().end(); ++iter3 ) { NameExpr *key = dynamic_cast( *iter3 ); assert( key ); for ( ; iter1 != st->get_members().end(); ++iter1 ) { if ( key->get_name() == (*iter1)->get_name() ) { (*iter1)->print( cout ); cout << key->get_name() << endl; ObjectDecl *fred = dynamic_cast( *iter1 ); assert( fred ); StructInstType *mary = dynamic_cast( fred->get_type() ); assert( mary ); st = mary->get_baseStruct(); iter1 = st->get_members().begin(); break; } // if } // for } // for ObjectDecl *fred = dynamic_cast( *iter1 ); assert( fred ); initContext = fred->get_type(); (*listInit->begin_initializers())->accept( *this ); } // if } // for } else if ( UnionInstType *st = dynamic_cast(initContext) ) { DeclarationWithType *dt = dynamic_cast( *st->get_baseUnion()->get_members().begin() ); initContext = dt->get_type(); (*listInit->begin_initializers())->accept( *this ); } // if #endif } // ConstructorInit - fall back on C-style initializer void Resolver::fallbackInit( ConstructorInit * ctorInit ) { // could not find valid constructor, or found an intrinsic constructor // fall back on C-style initializer delete ctorInit->get_ctor(); ctorInit->set_ctor( NULL ); delete ctorInit->get_dtor(); ctorInit->set_dtor( NULL ); maybeAccept( ctorInit->get_init(), *this ); } // needs to be callable from outside the resolver, so this is a standalone function void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) { assert( ctorInit ); Resolver resolver( indexer ); ctorInit->accept( resolver ); } void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) { assert( stmtExpr ); Resolver resolver( indexer ); stmtExpr->accept( resolver ); } void Resolver::visit( ConstructorInit *ctorInit ) { // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit maybeAccept( ctorInit->get_ctor(), *this ); maybeAccept( ctorInit->get_dtor(), *this ); // found a constructor - can get rid of C-style initializer delete ctorInit->get_init(); ctorInit->set_init( NULL ); // intrinsic single parameter constructors and destructors do nothing. Since this was // implicitly generated, there's no way for it to have side effects, so get rid of it // to clean up generated code. if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_ctor() ) ) { delete ctorInit->get_ctor(); ctorInit->set_ctor( NULL ); } if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->get_dtor() ) ) { delete ctorInit->get_dtor(); ctorInit->set_dtor( NULL ); } // xxx - todo -- what about arrays? // if ( dtor == NULL && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) { // // can reduce the constructor down to a SingleInit using the // // second argument from the ctor call, since // delete ctorInit->get_ctor(); // ctorInit->set_ctor( NULL ); // Expression * arg = // ctorInit->set_init( new SingleInit( arg ) ); // } } } // namespace ResolvExpr // Local Variables: // // tab-width: 4 // // mode: c++ // // compile-command: "make install" // // End: //