// // 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. // // GenInit.cc -- // // Author : Rob Schluntz // Created On : Mon May 18 07:44:20 2015 // Last Modified By : Peter A. Buhr // Last Modified On : Fri Mar 17 09:12:36 2017 // Update Count : 183 // #include #include #include "InitTweak.h" #include "GenInit.h" #include "Common/PassVisitor.h" #include "GenPoly/DeclMutator.h" #include "GenPoly/PolyMutator.h" #include "GenPoly/ScopedSet.h" #include "ResolvExpr/typeops.h" #include "SynTree/Declaration.h" #include "SynTree/Expression.h" #include "SynTree/Initializer.h" #include "SynTree/Mutator.h" #include "SynTree/Statement.h" #include "SynTree/Type.h" #include "SymTab/Autogen.h" #include "SymTab/Mangler.h" namespace InitTweak { class ReturnFixer final : public GenPoly::PolyMutator { public: /// consistently allocates a temporary variable for the return value /// of a function so that anything which the resolver decides can be constructed /// into the return type of a function can be returned. static void makeReturnTemp( std::list< Declaration * > &translationUnit ); typedef GenPoly::PolyMutator Parent; using Parent::mutate; virtual DeclarationWithType * mutate( FunctionDecl *functionDecl ) override; virtual Statement * mutate( ReturnStmt * returnStmt ) override; protected: FunctionType * ftype; std::string funcName; }; class CtorDtor final : public GenPoly::PolyMutator { public: typedef GenPoly::PolyMutator Parent; using Parent::mutate; /// create constructor and destructor statements for object declarations. /// the actual call statements will be added in after the resolver has run /// so that the initializer expression is only removed if a constructor is found /// and the same destructor call is inserted in all of the appropriate locations. static void generateCtorDtor( std::list< Declaration * > &translationUnit ); virtual DeclarationWithType * mutate( ObjectDecl * ) override; virtual DeclarationWithType * mutate( FunctionDecl *functionDecl ) override; // should not traverse into any of these declarations to find objects // that need to be constructed or destructed virtual Declaration* mutate( StructDecl *aggregateDecl ) override; virtual Declaration* mutate( UnionDecl *aggregateDecl ) override { return aggregateDecl; } virtual Declaration* mutate( EnumDecl *aggregateDecl ) override { return aggregateDecl; } virtual Declaration* mutate( TraitDecl *aggregateDecl ) override { return aggregateDecl; } virtual TypeDecl* mutate( TypeDecl *typeDecl ) override { return typeDecl; } virtual Declaration* mutate( TypedefDecl *typeDecl ) override { return typeDecl; } virtual Type * mutate( FunctionType *funcType ) override { return funcType; } virtual CompoundStmt * mutate( CompoundStmt * compoundStmt ) override; private: // set of mangled type names for which a constructor or destructor exists in the current scope. // these types require a ConstructorInit node to be generated, anything else is a POD type and thus // should not have a ConstructorInit generated. bool isManaged( ObjectDecl * objDecl ) const ; // determine if object is managed bool isManaged( Type * type ) const; // determine if type is managed void handleDWT( DeclarationWithType * dwt ); // add type to managed if ctor/dtor GenPoly::ScopedSet< std::string > managedTypes; bool inFunction = false; }; class HoistArrayDimension final : public GenPoly::DeclMutator { public: typedef GenPoly::DeclMutator Parent; /// hoist dimension from array types in object declaration so that it uses a single /// const variable of type size_t, so that side effecting array dimensions are only /// computed once. static void hoistArrayDimension( std::list< Declaration * > & translationUnit ); private: using Parent::mutate; virtual DeclarationWithType * mutate( ObjectDecl * objectDecl ) override; virtual DeclarationWithType * mutate( FunctionDecl *functionDecl ) override; // should not traverse into any of these declarations to find objects // that need to be constructed or destructed virtual Declaration* mutate( StructDecl *aggregateDecl ) override { return aggregateDecl; } virtual Declaration* mutate( UnionDecl *aggregateDecl ) override { return aggregateDecl; } virtual Declaration* mutate( EnumDecl *aggregateDecl ) override { return aggregateDecl; } virtual Declaration* mutate( TraitDecl *aggregateDecl ) override { return aggregateDecl; } virtual TypeDecl* mutate( TypeDecl *typeDecl ) override { return typeDecl; } virtual Declaration* mutate( TypedefDecl *typeDecl ) override { return typeDecl; } virtual Type* mutate( FunctionType *funcType ) override { return funcType; } void hoist( Type * type ); Type::StorageClasses storageClasses; bool inFunction = false; }; void genInit( std::list< Declaration * > & translationUnit ) { ReturnFixer::makeReturnTemp( translationUnit ); HoistArrayDimension::hoistArrayDimension( translationUnit ); CtorDtor::generateCtorDtor( translationUnit ); } void ReturnFixer::makeReturnTemp( std::list< Declaration * > & translationUnit ) { ReturnFixer fixer; mutateAll( translationUnit, fixer ); } Statement *ReturnFixer::mutate( ReturnStmt *returnStmt ) { std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals(); assert( returnVals.size() == 0 || returnVals.size() == 1 ); // hands off if the function returns an lvalue - we don't want to allocate a temporary if a variable's address // is being returned if ( returnStmt->get_expr() && returnVals.size() == 1 && ! returnVals.front()->get_type()->get_lvalue() ) { // explicitly construct the return value using the return expression and the retVal object assertf( returnVals.front()->get_name() != "", "Function %s has unnamed return value\n", funcName.c_str() ); UntypedExpr *construct = new UntypedExpr( new NameExpr( "?{}" ) ); construct->get_args().push_back( new AddressExpr( new VariableExpr( returnVals.front() ) ) ); construct->get_args().push_back( returnStmt->get_expr() ); stmtsToAdd.push_back(new ExprStmt(noLabels, construct)); // return the retVal object returnStmt->set_expr( new VariableExpr( returnVals.front() ) ); } // if return returnStmt; } DeclarationWithType* ReturnFixer::mutate( FunctionDecl *functionDecl ) { ValueGuard< FunctionType * > oldFtype( ftype ); ValueGuard< std::string > oldFuncName( funcName ); ftype = functionDecl->get_functionType(); funcName = functionDecl->get_name(); return Parent::mutate( functionDecl ); } // precompute array dimension expression, because constructor generation may duplicate it, // which would be incorrect if it is a side-effecting computation. void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) { HoistArrayDimension hoister; hoister.mutateDeclarationList( translationUnit ); } DeclarationWithType * HoistArrayDimension::mutate( ObjectDecl * objectDecl ) { storageClasses = objectDecl->get_storageClasses(); DeclarationWithType * temp = Parent::mutate( objectDecl ); hoist( objectDecl->get_type() ); return temp; } void HoistArrayDimension::hoist( Type * type ) { // if in function, generate const size_t var static UniqueName dimensionName( "_array_dim" ); // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension. if ( ! inFunction ) return; if ( storageClasses.is_static ) return; if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) { if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist? // don't need to hoist dimension if it's a constexpr - only need to if there's potential for side effects. if ( isConstExpr( arrayType->get_dimension() ) ) return; ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, SymTab::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) ); arrayDimension->get_type()->set_const( true ); arrayType->set_dimension( new VariableExpr( arrayDimension ) ); addDeclaration( arrayDimension ); hoist( arrayType->get_base() ); return; } } DeclarationWithType * HoistArrayDimension::mutate( FunctionDecl *functionDecl ) { ValueGuard< bool > oldInFunc( inFunction ); inFunction = true; DeclarationWithType * decl = Parent::mutate( functionDecl ); return decl; } void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) { CtorDtor ctordtor; mutateAll( translationUnit, ctordtor ); } bool CtorDtor::isManaged( Type * type ) const { // need to clear and reset qualifiers when determining if a type is managed ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() ); type->get_qualifiers() = Type::Qualifiers(); if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) { // tuple is also managed if any of its components are managed if ( std::any_of( tupleType->get_types().begin(), tupleType->get_types().end(), [&](Type * type) { return isManaged( type ); }) ) { return true; } } // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) return managedTypes.find( SymTab::Mangler::mangle( type ) ) != managedTypes.end() || GenPoly::isPolyType( type ); } bool CtorDtor::isManaged( ObjectDecl * objDecl ) const { Type * type = objDecl->get_type(); while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) { type = at->get_base(); } return isManaged( type ); } void CtorDtor::handleDWT( DeclarationWithType * dwt ) { // if this function is a user-defined constructor or destructor, mark down the type as "managed" if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && isCtorDtor( dwt->get_name() ) ) { std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters(); assert( ! params.empty() ); PointerType * type = safe_dynamic_cast< PointerType * >( params.front()->get_type() ); managedTypes.insert( SymTab::Mangler::mangle( type->get_base() ) ); } } ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) { // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor assertf( objDecl, "genCtorDtor passed null objDecl" ); std::list< Statement * > stmts; InitExpander srcParam( maybeClone( arg ) ); SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl ); assert( stmts.size() <= 1 ); return stmts.size() == 1 ? safe_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr; } ConstructorInit * genCtorInit( ObjectDecl * objDecl ) { // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor // for each constructable object std::list< Statement * > ctor; std::list< Statement * > dtor; InitExpander srcParam( objDecl->get_init() ); InitExpander nullParam( (Initializer *)NULL ); SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl ); SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false ); // Currently genImplicitCall produces a single Statement - a CompoundStmt // which wraps everything that needs to happen. As such, it's technically // possible to use a Statement ** in the above calls, but this is inherently // unsafe, so instead we take the slightly less efficient route, but will be // immediately informed if somehow the above assumption is broken. In this case, // we could always wrap the list of statements at this point with a CompoundStmt, // but it seems reasonable at the moment for this to be done by genImplicitCall // itself. It is possible that genImplicitCall produces no statements (e.g. if // an array type does not have a dimension). In this case, it's fine to ignore // the object for the purposes of construction. assert( ctor.size() == dtor.size() && ctor.size() <= 1 ); if ( ctor.size() == 1 ) { // need to remember init expression, in case no ctors exist // if ctor does exist, want to use ctor expression instead of init // push this decision to the resolver assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) ); return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ); } return nullptr; } DeclarationWithType * CtorDtor::mutate( ObjectDecl * objDecl ) { handleDWT( objDecl ); // hands off if @=, extern, builtin, etc. // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C if ( tryConstruct( objDecl ) && ( isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) { // constructed objects cannot be designated if ( isDesignated( objDecl->get_init() ) ) throw SemanticError( "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n", objDecl ); // constructed objects should not have initializers nested too deeply if ( ! checkInitDepth( objDecl ) ) throw SemanticError( "Managed object's initializer is too deep ", objDecl ); objDecl->set_init( genCtorInit( objDecl ) ); } return Parent::mutate( objDecl ); } DeclarationWithType * CtorDtor::mutate( FunctionDecl *functionDecl ) { ValueGuard< bool > oldInFunc = inFunction; inFunction = true; handleDWT( functionDecl ); managedTypes.beginScope(); // go through assertions and recursively add seen ctor/dtors for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) { for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) { handleDWT( assertion ); } } // parameters should not be constructed and destructed, so don't mutate FunctionType functionDecl->set_statements( maybeMutate( functionDecl->get_statements(), *this ) ); managedTypes.endScope(); return functionDecl; } Declaration* CtorDtor::mutate( StructDecl *aggregateDecl ) { // don't construct members, but need to take note if there is a managed member, // because that means that this type is also managed for ( Declaration * member : aggregateDecl->get_members() ) { if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) { if ( isManaged( field ) ) { StructInstType inst( Type::Qualifiers(), aggregateDecl ); managedTypes.insert( SymTab::Mangler::mangle( &inst ) ); break; } } } return aggregateDecl; } CompoundStmt * CtorDtor::mutate( CompoundStmt * compoundStmt ) { managedTypes.beginScope(); CompoundStmt * stmt = Parent::mutate( compoundStmt ); managedTypes.endScope(); return stmt; } } // namespace InitTweak // Local Variables: // // tab-width: 4 // // mode: c++ // // compile-command: "make install" // // End: //