// // 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. // // Validate.cc -- // // Author : Richard C. Bilson // Created On : Sun May 17 21:50:04 2015 // Last Modified By : Peter A. Buhr // Last Modified On : Thu Apr 7 16:45:30 2016 // Update Count : 243 // // The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be // as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is // complete, including: // // - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or // union. // // - All enumeration constants have type EnumInstType. // // - The type "void" never occurs in lists of function parameter or return types; neither do tuple types. A function // taking no arguments has no argument types, and tuples are flattened. // // - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated // by the particular set of type arguments. // // - Every declaration is assigned a unique id. // // - No typedef declarations or instances exist; the actual type is substituted for each instance. // // - Each type, struct, and union definition is followed by an appropriate assignment operator. // // - Each use of a struct or union is connected to a complete definition of that struct or union, even if that // definition occurs later in the input. #include #include #include "Common/utility.h" #include "Common/UniqueName.h" #include "Validate.h" #include "SynTree/Visitor.h" #include "SynTree/Mutator.h" #include "SynTree/Type.h" #include "SynTree/Expression.h" #include "SynTree/Statement.h" #include "SynTree/TypeSubstitution.h" #include "Indexer.h" #include "FixFunction.h" // #include "ImplementationType.h" #include "GenPoly/DeclMutator.h" #include "AddVisit.h" #include "MakeLibCfa.h" #include "TypeEquality.h" #include "ResolvExpr/typeops.h" #define debugPrint( x ) if ( doDebug ) { std::cout << x; } namespace SymTab { class HoistStruct : public Visitor { public: /// Flattens nested struct types static void hoistStruct( std::list< Declaration * > &translationUnit ); std::list< Declaration * > &get_declsToAdd() { return declsToAdd; } virtual void visit( StructDecl *aggregateDecl ); virtual void visit( UnionDecl *aggregateDecl ); virtual void visit( CompoundStmt *compoundStmt ); virtual void visit( SwitchStmt *switchStmt ); virtual void visit( ChooseStmt *chooseStmt ); // virtual void visit( CaseStmt *caseStmt ); private: HoistStruct(); template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl ); std::list< Declaration * > declsToAdd; bool inStruct; }; /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers. class Pass1 : public Visitor { typedef Visitor Parent; virtual void visit( EnumDecl *aggregateDecl ); virtual void visit( FunctionType *func ); }; /// Associates forward declarations of aggregates with their definitions class Pass2 : public Indexer { typedef Indexer Parent; public: Pass2( bool doDebug, const Indexer *indexer ); private: virtual void visit( StructInstType *structInst ); virtual void visit( UnionInstType *unionInst ); virtual void visit( TraitInstType *contextInst ); virtual void visit( StructDecl *structDecl ); virtual void visit( UnionDecl *unionDecl ); virtual void visit( TypeInstType *typeInst ); const Indexer *indexer; typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType; typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType; ForwardStructsType forwardStructs; ForwardUnionsType forwardUnions; }; /// Replaces array and function types in forall lists by appropriate pointer type class Pass3 : public Indexer { typedef Indexer Parent; public: Pass3( const Indexer *indexer ); private: virtual void visit( ObjectDecl *object ); virtual void visit( FunctionDecl *func ); const Indexer *indexer; }; class AutogenerateRoutines : public Visitor { public: /// Generates assignment operators for aggregate types as required static void autogenerateRoutines( std::list< Declaration * > &translationUnit ); std::list< Declaration * > &get_declsToAdd() { return declsToAdd; } virtual void visit( EnumDecl *enumDecl ); virtual void visit( StructDecl *structDecl ); virtual void visit( UnionDecl *structDecl ); virtual void visit( TypeDecl *typeDecl ); virtual void visit( TraitDecl *ctxDecl ); virtual void visit( FunctionDecl *functionDecl ); virtual void visit( FunctionType *ftype ); virtual void visit( PointerType *ftype ); virtual void visit( CompoundStmt *compoundStmt ); virtual void visit( SwitchStmt *switchStmt ); virtual void visit( ChooseStmt *chooseStmt ); // virtual void visit( CaseStmt *caseStmt ); AutogenerateRoutines() : functionNesting( 0 ) {} private: template< typename StmtClass > void visitStatement( StmtClass *stmt ); std::list< Declaration * > declsToAdd; std::set< std::string > structsDone; unsigned int functionNesting; // current level of nested functions }; class ReturnChecker : public Visitor { public: /// Checks that return statements return nothing if their return type is void /// and return something if the return type is non-void. static void checkFunctionReturns( std::list< Declaration * > & translationUnit ); private: virtual void visit( FunctionDecl * functionDecl ); virtual void visit( ReturnStmt * returnStmt ); std::list< DeclarationWithType * > returnVals; }; class EliminateTypedef : public Mutator { public: EliminateTypedef() : scopeLevel( 0 ) {} /// Replaces typedefs by forward declarations static void eliminateTypedef( std::list< Declaration * > &translationUnit ); private: virtual Declaration *mutate( TypedefDecl *typeDecl ); virtual TypeDecl *mutate( TypeDecl *typeDecl ); virtual DeclarationWithType *mutate( FunctionDecl *funcDecl ); virtual DeclarationWithType *mutate( ObjectDecl *objDecl ); virtual CompoundStmt *mutate( CompoundStmt *compoundStmt ); virtual Type *mutate( TypeInstType *aggregateUseType ); virtual Expression *mutate( CastExpr *castExpr ); virtual Declaration *mutate( StructDecl * structDecl ); virtual Declaration *mutate( UnionDecl * unionDecl ); virtual Declaration *mutate( EnumDecl * enumDecl ); virtual Declaration *mutate( TraitDecl * contextDecl ); template AggDecl *handleAggregate( AggDecl * aggDecl ); typedef std::map< std::string, std::pair< TypedefDecl *, int > > TypedefMap; TypedefMap typedefNames; int scopeLevel; }; class CompoundLiteral : public GenPoly::DeclMutator { DeclarationNode::StorageClass storageclass = DeclarationNode::NoStorageClass; virtual DeclarationWithType * mutate( ObjectDecl *objectDecl ); virtual Expression *mutate( CompoundLiteralExpr *compLitExpr ); }; void validate( std::list< Declaration * > &translationUnit, bool doDebug ) { Pass1 pass1; Pass2 pass2( doDebug, 0 ); Pass3 pass3( 0 ); CompoundLiteral compoundliteral; EliminateTypedef::eliminateTypedef( translationUnit ); HoistStruct::hoistStruct( translationUnit ); acceptAll( translationUnit, pass1 ); acceptAll( translationUnit, pass2 ); ReturnChecker::checkFunctionReturns( translationUnit ); mutateAll( translationUnit, compoundliteral ); AutogenerateRoutines::autogenerateRoutines( translationUnit ); acceptAll( translationUnit, pass3 ); } void validateType( Type *type, const Indexer *indexer ) { Pass1 pass1; Pass2 pass2( false, indexer ); Pass3 pass3( indexer ); type->accept( pass1 ); type->accept( pass2 ); type->accept( pass3 ); } template< typename Visitor > void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) { std::list< Declaration * >::iterator i = translationUnit.begin(); while ( i != translationUnit.end() ) { (*i)->accept( visitor ); std::list< Declaration * >::iterator next = i; next++; if ( ! visitor.get_declsToAdd().empty() ) { translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() ); } // if i = next; } // while } void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) { HoistStruct hoister; acceptAndAdd( translationUnit, hoister, true ); } HoistStruct::HoistStruct() : inStruct( false ) { } void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) { std::list< Declaration * >::iterator i = declList.begin(); while ( i != declList.end() ) { std::list< Declaration * >::iterator next = i; ++next; if ( pred( *i ) ) { if ( doDelete ) { delete *i; } // if declList.erase( i ); } // if i = next; } // while } bool isStructOrUnion( Declaration *decl ) { return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ); } template< typename AggDecl > void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) { if ( inStruct ) { // Add elements in stack order corresponding to nesting structure. declsToAdd.push_front( aggregateDecl ); Visitor::visit( aggregateDecl ); } else { inStruct = true; Visitor::visit( aggregateDecl ); inStruct = false; } // if // Always remove the hoisted aggregate from the inner structure. filter( aggregateDecl->get_members(), isStructOrUnion, false ); } void HoistStruct::visit( StructDecl *aggregateDecl ) { handleAggregate( aggregateDecl ); } void HoistStruct::visit( UnionDecl *aggregateDecl ) { handleAggregate( aggregateDecl ); } void HoistStruct::visit( CompoundStmt *compoundStmt ) { addVisit( compoundStmt, *this ); } void HoistStruct::visit( SwitchStmt *switchStmt ) { addVisit( switchStmt, *this ); } void HoistStruct::visit( ChooseStmt *switchStmt ) { addVisit( switchStmt, *this ); } // void HoistStruct::visit( CaseStmt *caseStmt ) { // addVisit( caseStmt, *this ); // } void Pass1::visit( EnumDecl *enumDecl ) { // Set the type of each member of the enumeration to be EnumConstant for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) { ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i ); assert( obj ); // obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) ); BasicType * enumType = new BasicType( Type::Qualifiers(), BasicType::SignedInt ); obj->set_type( enumType ) ; } // for Parent::visit( enumDecl ); } namespace { template< typename DWTIterator > void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) { // the only case in which "void" is valid is where it is the only one in the list; then it should be removed // entirely other fix ups are handled by the FixFunction class if ( begin == end ) return; FixFunction fixer; DWTIterator i = begin; *i = (*i )->acceptMutator( fixer ); if ( fixer.get_isVoid() ) { DWTIterator j = i; ++i; func->get_parameters().erase( j ); if ( i != end ) { throw SemanticError( "invalid type void in function type ", func ); } // if } else { ++i; for ( ; i != end; ++i ) { FixFunction fixer; *i = (*i )->acceptMutator( fixer ); if ( fixer.get_isVoid() ) { throw SemanticError( "invalid type void in function type ", func ); } // if } // for } // if } } void Pass1::visit( FunctionType *func ) { // Fix up parameters and return types fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func ); fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func ); Visitor::visit( func ); } Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) { if ( other_indexer ) { indexer = other_indexer; } else { indexer = this; } // if } void Pass2::visit( StructInstType *structInst ) { Parent::visit( structInst ); StructDecl *st = indexer->lookupStruct( structInst->get_name() ); // it's not a semantic error if the struct is not found, just an implicit forward declaration if ( st ) { //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() ); structInst->set_baseStruct( st ); } // if if ( ! st || st->get_members().empty() ) { // use of forward declaration forwardStructs[ structInst->get_name() ].push_back( structInst ); } // if } void Pass2::visit( UnionInstType *unionInst ) { Parent::visit( unionInst ); UnionDecl *un = indexer->lookupUnion( unionInst->get_name() ); // it's not a semantic error if the union is not found, just an implicit forward declaration if ( un ) { unionInst->set_baseUnion( un ); } // if if ( ! un || un->get_members().empty() ) { // use of forward declaration forwardUnions[ unionInst->get_name() ].push_back( unionInst ); } // if } void Pass2::visit( TraitInstType *contextInst ) { Parent::visit( contextInst ); TraitDecl *ctx = indexer->lookupTrait( contextInst->get_name() ); if ( ! ctx ) { throw SemanticError( "use of undeclared context " + contextInst->get_name() ); } // if for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) { for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) { if ( TraitInstType *otherCtx = dynamic_cast< TraitInstType * >(*assert ) ) { cloneAll( otherCtx->get_members(), contextInst->get_members() ); } else { contextInst->get_members().push_back( (*assert )->clone() ); } // if } // for } // for if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) { throw SemanticError( "incorrect number of context parameters: ", contextInst ); } // if applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), ctx->get_members().begin(), ctx->get_members().end(), back_inserter( contextInst->get_members() ) ); } void Pass2::visit( StructDecl *structDecl ) { if ( ! structDecl->get_members().empty() ) { ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() ); if ( fwds != forwardStructs.end() ) { for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) { (*inst )->set_baseStruct( structDecl ); } // for forwardStructs.erase( fwds ); } // if } // if Indexer::visit( structDecl ); } void Pass2::visit( UnionDecl *unionDecl ) { if ( ! unionDecl->get_members().empty() ) { ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() ); if ( fwds != forwardUnions.end() ) { for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) { (*inst )->set_baseUnion( unionDecl ); } // for forwardUnions.erase( fwds ); } // if } // if Indexer::visit( unionDecl ); } void Pass2::visit( TypeInstType *typeInst ) { if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) { if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) { typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype ); } // if } // if } Pass3::Pass3( const Indexer *other_indexer ) : Indexer( false ) { if ( other_indexer ) { indexer = other_indexer; } else { indexer = this; } // if } /// Fix up assertions void forallFixer( Type *func ) { for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) { std::list< DeclarationWithType * > toBeDone, nextRound; toBeDone.splice( toBeDone.end(), (*type )->get_assertions() ); while ( ! toBeDone.empty() ) { for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) { if ( TraitInstType *ctx = dynamic_cast< TraitInstType * >( (*assertion )->get_type() ) ) { for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) { DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i ); assert( dwt ); nextRound.push_back( dwt->clone() ); } delete ctx; } else { FixFunction fixer; *assertion = (*assertion )->acceptMutator( fixer ); if ( fixer.get_isVoid() ) { throw SemanticError( "invalid type void in assertion of function ", func ); } (*type )->get_assertions().push_back( *assertion ); } // if } // for toBeDone.clear(); toBeDone.splice( toBeDone.end(), nextRound ); } // while } // for } void Pass3::visit( ObjectDecl *object ) { forallFixer( object->get_type() ); if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) { forallFixer( pointer->get_base() ); } // if Parent::visit( object ); object->fixUniqueId(); } void Pass3::visit( FunctionDecl *func ) { forallFixer( func->get_type() ); Parent::visit( func ); func->fixUniqueId(); } static const std::list< std::string > noLabels; void AutogenerateRoutines::autogenerateRoutines( std::list< Declaration * > &translationUnit ) { AutogenerateRoutines visitor; acceptAndAdd( translationUnit, visitor, false ); } template< typename OutputIterator > void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) { ObjectDecl *obj = dynamic_cast( member ); // unnamed bit fields are not copied as they cannot be accessed if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return; UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) ); UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) ); derefExpr->get_args().push_back( new VariableExpr( dstParam ) ); // do something special for unnamed members Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) ); assignExpr->get_args().push_back( dstselect ); Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) ); assignExpr->get_args().push_back( srcselect ); *out++ = new ExprStmt( noLabels, assignExpr ); } template< typename OutputIterator > void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) { static UniqueName indexName( "_index" ); // for a flexible array member nothing is done -- user must define own assignment if ( ! array->get_dimension() ) return; ObjectDecl *index = new ObjectDecl( indexName.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 ); *out++ = new DeclStmt( noLabels, index ); UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) ); init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) ); init->get_args().push_back( new NameExpr( "0" ) ); Statement *initStmt = new ExprStmt( noLabels, init ); std::list initList; initList.push_back( initStmt ); UntypedExpr *cond = new UntypedExpr( new NameExpr( "?get_args().push_back( new VariableExpr( index ) ); cond->get_args().push_back( array->get_dimension()->clone() ); UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) ); inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) ); UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) ); UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) ); derefExpr->get_args().push_back( new VariableExpr( dstParam ) ); Expression *dstselect = new MemberExpr( member, derefExpr ); UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) ); dstIndex->get_args().push_back( dstselect ); dstIndex->get_args().push_back( new VariableExpr( index ) ); assignExpr->get_args().push_back( dstIndex ); Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) ); UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) ); srcIndex->get_args().push_back( srcselect ); srcIndex->get_args().push_back( new VariableExpr( index ) ); assignExpr->get_args().push_back( srcIndex ); *out++ = new ForStmt( noLabels, initList, cond, inc, new ExprStmt( noLabels, assignExpr ) ); } template< typename OutputIterator > void makeUnionFieldsAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, UnionInstType *unionType, OutputIterator out ) { UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) ); copy->get_args().push_back( new VariableExpr( dstParam ) ); copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) ); copy->get_args().push_back( new SizeofExpr( unionType ) ); *out++ = new ExprStmt( noLabels, copy ); } //E ?=?(E volatile*, int), // ?=?(E _Atomic volatile*, int); void makeEnumAssignment( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) { FunctionType *assignType = new FunctionType( Type::Qualifiers(), false ); ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 ); assignType->get_returnVals().push_back( returnVal ); // need two assignment operators with different types FunctionType * assignType2 = assignType->clone(); // E ?=?(E volatile *, E) Type *etype = refType->clone(); // etype->get_qualifiers() += Type::Qualifiers(false, true, false, false, false, false); ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), etype ), 0 ); assignType->get_parameters().push_back( dstParam ); ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, etype->clone(), 0 ); assignType->get_parameters().push_back( srcParam ); // E ?=?(E volatile *, int) assignType2->get_parameters().push_back( dstParam->clone() ); BasicType * paramType = new BasicType(Type::Qualifiers(), BasicType::SignedInt); ObjectDecl *srcParam2 = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, paramType, 0 ); assignType2->get_parameters().push_back( srcParam2 ); // Routines at global scope marked "static" to prevent multiple definitions is separate translation units // because each unit generates copies of the default routines for each aggregate. // since there is no definition, these should not be inline // make these intrinsic so that the code generator does not make use of them FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, 0, false, false ); assignDecl->fixUniqueId(); FunctionDecl *assignDecl2 = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType2, 0, false, false ); assignDecl2->fixUniqueId(); // these should be built in the same way that the prelude // functions are, so build a list containing the prototypes // and allow MakeLibCfa to autogenerate the bodies. std::list< Declaration * > assigns; assigns.push_back( assignDecl ); assigns.push_back( assignDecl2 ); LibCfa::makeLibCfa( assigns ); // need to remove the prototypes, since this may be nested in a routine for (int start = 0, end = assigns.size()/2; start < end; start++) { delete assigns.front(); assigns.pop_front(); } // for declsToAdd.insert( declsToAdd.begin(), assigns.begin(), assigns.end() ); } /// Clones a reference type, replacing any parameters it may have with a clone of the provided list template< typename GenericInstType > GenericInstType *cloneWithParams( GenericInstType *refType, const std::list< Expression* >& params ) { GenericInstType *clone = refType->clone(); clone->get_parameters().clear(); cloneAll( params, clone->get_parameters() ); return clone; } /// Creates a new type decl that's the same as src, but renamed and with only the ?=? assertion (for complete types only) TypeDecl *cloneAndRename( TypeDecl *src, const std::string &name ) { TypeDecl *dst = new TypeDecl( name, src->get_storageClass(), 0, src->get_kind() ); if ( src->get_kind() == TypeDecl::Any ) { // just include assignment operator assertion TypeInstType *assignParamType = new TypeInstType( Type::Qualifiers(), name, dst ); FunctionType *assignFunctionType = new FunctionType( Type::Qualifiers(), false ); assignFunctionType->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, assignParamType->clone(), 0 ) ); assignFunctionType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), assignParamType->clone() ), 0 ) ); assignFunctionType->get_parameters().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, assignParamType, 0 ) ); FunctionDecl *assignAssert = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, assignFunctionType, 0, false, false ); dst->get_assertions().push_back( assignAssert ); } return dst; } Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) { FunctionType *assignType = new FunctionType( Type::Qualifiers(), false ); // Make function polymorphic in same parameters as generic struct, if applicable bool isGeneric = false; // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union) std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters(); std::list< Expression* > structParams; // List of matching parameters to put on types TypeSubstitution genericSubs; // Substitutions to make to member types of struct for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) { isGeneric = true; TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() ); assignType->get_forall().push_back( typeParam ); TypeInstType *newParamType = new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ); genericSubs.add( (*param)->get_name(), newParamType ); structParams.push_back( new TypeExpr( newParamType ) ); } ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 ); assignType->get_returnVals().push_back( returnVal ); ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, structParams ) ), 0 ); assignType->get_parameters().push_back( dstParam ); ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, structParams ), 0 ); assignType->get_parameters().push_back( srcParam ); // Routines at global scope marked "static" to prevent multiple definitions is separate translation units // because each unit generates copies of the default routines for each aggregate. FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false ); assignDecl->fixUniqueId(); for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) { if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) { // query the type qualifiers of this field and skip assigning it if it is marked const. // If it is an array type, we need to strip off the array layers to find its qualifiers. Type * type = dwt->get_type(); while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) { type = at->get_base(); } if ( type->get_qualifiers().isConst ) { // don't assign const members continue; } if ( isGeneric ) { // rewrite member type in terms of the type variables on this operator DeclarationWithType *fixedMember = dwt->clone(); genericSubs.apply( fixedMember ); // assign to both destination and return value if ( ArrayType *array = dynamic_cast< ArrayType * >( fixedMember->get_type() ) ) { makeArrayAssignment( srcParam, dstParam, fixedMember, array, back_inserter( assignDecl->get_statements()->get_kids() ) ); makeArrayAssignment( srcParam, returnVal, fixedMember, array, back_inserter( assignDecl->get_statements()->get_kids() ) ); } else { makeScalarAssignment( srcParam, dstParam, fixedMember, back_inserter( assignDecl->get_statements()->get_kids() ) ); makeScalarAssignment( srcParam, returnVal, fixedMember, back_inserter( assignDecl->get_statements()->get_kids() ) ); } // if } else { // assign to destination if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) { makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) ); } else { makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) ); } // if } // if } // if } // for if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) ); return assignDecl; } Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) { FunctionType *assignType = new FunctionType( Type::Qualifiers(), false ); // Make function polymorphic in same parameters as generic union, if applicable bool isGeneric = false; // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for struct) std::list< TypeDecl* >& genericParams = aggregateDecl->get_parameters(); std::list< Expression* > unionParams; // List of matching parameters to put on types for ( std::list< TypeDecl* >::const_iterator param = genericParams.begin(); param != genericParams.end(); ++param ) { isGeneric = true; TypeDecl *typeParam = cloneAndRename( *param, "_autoassign_" + aggregateDecl->get_name() + "_" + (*param)->get_name() ); assignType->get_forall().push_back( typeParam ); unionParams.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeParam->get_name(), typeParam ) ) ); } ObjectDecl *returnVal = new ObjectDecl( "_ret", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 ); assignType->get_returnVals().push_back( returnVal ); ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), cloneWithParams( refType, unionParams ) ), 0 ); assignType->get_parameters().push_back( dstParam ); ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, cloneWithParams( refType, unionParams ), 0 ); assignType->get_parameters().push_back( srcParam ); // Routines at global scope marked "static" to prevent multiple definitions is separate translation units // because each unit generates copies of the default routines for each aggregate. FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false ); assignDecl->fixUniqueId(); makeUnionFieldsAssignment( srcParam, dstParam, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) ); if ( isGeneric ) makeUnionFieldsAssignment( srcParam, returnVal, cloneWithParams( refType, unionParams ), back_inserter( assignDecl->get_statements()->get_kids() ) ); if ( ! isGeneric ) assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) ); return assignDecl; } void AutogenerateRoutines::visit( EnumDecl *enumDecl ) { if ( ! enumDecl->get_members().empty() ) { EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() ); // enumInst->set_baseEnum( enumDecl ); // declsToAdd.push_back( makeEnumAssignment( enumDecl, enumInst, functionNesting, declsToAdd ); } } void AutogenerateRoutines::visit( StructDecl *structDecl ) { if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) { StructInstType structInst( Type::Qualifiers(), structDecl->get_name() ); structInst.set_baseStruct( structDecl ); declsToAdd.push_back( makeStructAssignment( structDecl, &structInst, functionNesting ) ); structsDone.insert( structDecl->get_name() ); } // if } void AutogenerateRoutines::visit( UnionDecl *unionDecl ) { if ( ! unionDecl->get_members().empty() ) { UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() ); unionInst.set_baseUnion( unionDecl ); declsToAdd.push_back( makeUnionAssignment( unionDecl, &unionInst, functionNesting ) ); } // if } void AutogenerateRoutines::visit( TypeDecl *typeDecl ) { CompoundStmt *stmts = 0; TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false ); typeInst->set_baseType( typeDecl ); ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 ); ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 ); if ( typeDecl->get_base() ) { stmts = new CompoundStmt( std::list< Label >() ); UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) ); assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) ); assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) ); stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) ); } // if FunctionType *type = new FunctionType( Type::Qualifiers(), false ); type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) ); type->get_parameters().push_back( dst ); type->get_parameters().push_back( src ); FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false, false ); declsToAdd.push_back( func ); } void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) { for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) { statements.insert( i, new DeclStmt( noLabels, *decl ) ); } // for declsToAdd.clear(); } void AutogenerateRoutines::visit( FunctionType *) { // ensure that we don't add assignment ops for types defined as part of the function } void AutogenerateRoutines::visit( PointerType *) { // ensure that we don't add assignment ops for types defined as part of the pointer } void AutogenerateRoutines::visit( TraitDecl *) { // ensure that we don't add assignment ops for types defined as part of the context } template< typename StmtClass > inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) { std::set< std::string > oldStructs = structsDone; addVisit( stmt, *this ); structsDone = oldStructs; } void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) { maybeAccept( functionDecl->get_functionType(), *this ); acceptAll( functionDecl->get_oldDecls(), *this ); functionNesting += 1; maybeAccept( functionDecl->get_statements(), *this ); functionNesting -= 1; } void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) { visitStatement( compoundStmt ); } void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) { visitStatement( switchStmt ); } void AutogenerateRoutines::visit( ChooseStmt *switchStmt ) { visitStatement( switchStmt ); } // void AutogenerateRoutines::visit( CaseStmt *caseStmt ) { // visitStatement( caseStmt ); // } void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) { ReturnChecker checker; acceptAll( translationUnit, checker ); } void ReturnChecker::visit( FunctionDecl * functionDecl ) { std::list< DeclarationWithType * > oldReturnVals = returnVals; returnVals = functionDecl->get_functionType()->get_returnVals(); Visitor::visit( functionDecl ); returnVals = oldReturnVals; } void ReturnChecker::visit( ReturnStmt * returnStmt ) { if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) { throw SemanticError( "Non-void function returns no values: " , returnStmt ); } else if ( returnStmt->get_expr() != NULL && returnVals.size() == 0 ) { throw SemanticError( "void function returns values: " , returnStmt ); } } bool isTypedef( Declaration *decl ) { return dynamic_cast< TypedefDecl * >( decl ); } void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) { EliminateTypedef eliminator; mutateAll( translationUnit, eliminator ); filter( translationUnit, isTypedef, true ); } Type *EliminateTypedef::mutate( TypeInstType * typeInst ) { // instances of typedef types will come here. If it is an instance // of a typdef type, link the instance to its actual type. TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() ); if ( def != typedefNames.end() ) { Type *ret = def->second.first->get_base()->clone(); ret->get_qualifiers() += typeInst->get_qualifiers(); // place instance parameters on the typedef'd type if ( ! typeInst->get_parameters().empty() ) { ReferenceToType *rtt = dynamic_cast(ret); if ( ! rtt ) { throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name()); } rtt->get_parameters().clear(); cloneAll(typeInst->get_parameters(), rtt->get_parameters()); } // if delete typeInst; return ret; } // if return typeInst; } Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) { Declaration *ret = Mutator::mutate( tyDecl ); if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) { // typedef to the same name from the same scope // must be from the same type Type * t1 = tyDecl->get_base(); Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base(); if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) { throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() ); } } else { typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel ); } // if // When a typedef is a forward declaration: // typedef struct screen SCREEN; // the declaration portion must be retained: // struct screen; // because the expansion of the typedef is: // void rtn( SCREEN *p ) => void rtn( struct screen *p ) // hence the type-name "screen" must be defined. // Note, qualifiers on the typedef are superfluous for the forward declaration. if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) { return new StructDecl( aggDecl->get_name() ); } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) { return new UnionDecl( aggDecl->get_name() ); } else { return ret; } // if } TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) { TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() ); if ( i != typedefNames.end() ) { typedefNames.erase( i ) ; } // if return typeDecl; } DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) { TypedefMap oldNames = typedefNames; DeclarationWithType *ret = Mutator::mutate( funcDecl ); typedefNames = oldNames; return ret; } DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) { TypedefMap oldNames = typedefNames; DeclarationWithType *ret = Mutator::mutate( objDecl ); typedefNames = oldNames; // is the type a function? if ( FunctionType *funtype = dynamic_cast( ret->get_type() ) ) { // replace the current object declaration with a function declaration return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() ); } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) { throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl ); } // if return ret; } Expression *EliminateTypedef::mutate( CastExpr * castExpr ) { TypedefMap oldNames = typedefNames; Expression *ret = Mutator::mutate( castExpr ); typedefNames = oldNames; return ret; } CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) { TypedefMap oldNames = typedefNames; scopeLevel += 1; CompoundStmt *ret = Mutator::mutate( compoundStmt ); scopeLevel -= 1; std::list< Statement * >::iterator i = compoundStmt->get_kids().begin(); while ( i != compoundStmt->get_kids().end() ) { std::list< Statement * >::iterator next = i+1; if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) { if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) { delete *i; compoundStmt->get_kids().erase( i ); } // if } // if i = next; } // while typedefNames = oldNames; return ret; } // there may be typedefs nested within aggregates // in order for everything to work properly, these // should be removed as well template AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) { std::list::iterator it = aggDecl->get_members().begin(); for ( ; it != aggDecl->get_members().end(); ) { std::list< Declaration * >::iterator next = it+1; if ( dynamic_cast< TypedefDecl * >( *it ) ) { delete *it; aggDecl->get_members().erase( it ); } // if it = next; } return aggDecl; } Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) { Mutator::mutate( structDecl ); return handleAggregate( structDecl ); } Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) { Mutator::mutate( unionDecl ); return handleAggregate( unionDecl ); } Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) { Mutator::mutate( enumDecl ); return handleAggregate( enumDecl ); } Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) { Mutator::mutate( contextDecl ); return handleAggregate( contextDecl ); } DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) { storageclass = objectDecl->get_storageClass(); DeclarationWithType * temp = Mutator::mutate( objectDecl ); storageclass = DeclarationNode::NoStorageClass; return temp; } Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) { // transform [storage_class] ... (struct S){ 3, ... }; // into [storage_class] struct S temp = { 3, ... }; static UniqueName indexName( "_compLit" ); ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageclass, LinkageSpec::C, 0, compLitExpr->get_type(), compLitExpr->get_initializer() ); compLitExpr->set_type( 0 ); compLitExpr->set_initializer( 0 ); delete compLitExpr; DeclarationWithType * newtempvar = mutate( tempvar ); addDeclaration( newtempvar ); // add modified temporary to current block return new VariableExpr( newtempvar ); } } // namespace SymTab // Local Variables: // // tab-width: 4 // // mode: c++ // // compile-command: "make install" // // End: //