source: src/Tuples/TupleExpansion.cc @ d104b02

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 d104b02 was 9f10c4b8, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Add maybeImpureIgnoreUnique and convert tuple passes to use PassVisitor?

  • Property mode set to 100644
File size: 14.2 KB
RevLine 
[6eb8948]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// TupleAssignment.cc --
8//
9// Author           : Rodolfo G. Esteves
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
[d56e5bc]12// Last Modified On : Wed Jun 21 17:35:04 2017
13// Update Count     : 19
[6eb8948]14//
15
16#include <iterator>
17#include <iostream>
18#include <cassert>
19#include "Tuples.h"
[ab904dc]20#include "Common/PassVisitor.h"
21#include "Common/ScopedMap.h"
[f006f01]22#include "GenPoly/DeclMutator.h"
[ab904dc]23#include "InitTweak/GenInit.h"
24#include "InitTweak/InitTweak.h"
25#include "ResolvExpr/typeops.h"
26#include "SymTab/Mangler.h"
[f006f01]27#include "SynTree/Declaration.h"
[3c13c03]28#include "SynTree/Expression.h"
29#include "SynTree/Initializer.h"
[ab904dc]30#include "SynTree/Mutator.h"
31#include "SynTree/Statement.h"
32#include "SynTree/Type.h"
[6eb8948]33
34namespace Tuples {
[3c13c03]35        namespace {
[c93bc28]36                struct MemberTupleExpander final : public Mutator {
[bf32bb8]37                        typedef Mutator Parent;
[5f5083e]38                        using Parent::mutate;
39
40                        virtual Expression * mutate( UntypedMemberExpr * memberExpr ) override;
[bf32bb8]41                };
42
[9f10c4b8]43                struct UniqueExprExpander final : public WithDeclsToAdd {
44                        Expression * postmutate( UniqueExpr * unqExpr );
[141b786]45
46                        std::map< int, Expression * > decls; // not vector, because order added may not be increasing order
47
48                        ~UniqueExprExpander() {
49                                for ( std::pair<const int, Expression *> & p : decls ) {
50                                        delete p.second;
51                                }
52                        }
[3c13c03]53                };
54
[9f10c4b8]55                struct TupleAssignExpander {
56                        Expression * postmutate( TupleAssignExpr * tupleExpr );
[3c13c03]57                };
58
[c92c09c]59                struct TupleTypeReplacer : public WithDeclsToAdd, public WithGuards, public WithTypeSubstitution {
60                        Type * postmutate( TupleType * tupleType );
[3c13c03]61
[c92c09c]62                        void premutate( CompoundStmt * ) {
63                                GuardScope( typeMap );
[3c13c03]64                        }
65                  private:
[e6512c8]66                        ScopedMap< int, StructDecl * > typeMap;
[3c13c03]67                };
68
[c93bc28]69                struct TupleIndexExpander {
[ab904dc]70                        Expression * postmutate( TupleIndexExpr * tupleExpr );
[3c13c03]71                };
72
[9f10c4b8]73                struct TupleExprExpander final {
74                        Expression * postmutate( TupleExpr * tupleExpr );
[3c13c03]75                };
76        }
[f006f01]77
[bf32bb8]78        void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
79                MemberTupleExpander expander;
80                mutateAll( translationUnit, expander );
81        }
82
[aefcc3b]83        void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]84                PassVisitor<UniqueExprExpander> unqExpander;
85                mutateAll( translationUnit, unqExpander );
[aefcc3b]86        }
[3c13c03]87
[aefcc3b]88        void expandTuples( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]89                PassVisitor<TupleAssignExpander> assnExpander;
[3c13c03]90                mutateAll( translationUnit, assnExpander );
[f006f01]91
[c92c09c]92                PassVisitor<TupleTypeReplacer> replacer;
93                mutateAll( translationUnit, replacer );
[3c13c03]94
[ab904dc]95                PassVisitor<TupleIndexExpander> idxExpander;
[3c13c03]96                mutateAll( translationUnit, idxExpander );
97
[9f10c4b8]98                PassVisitor<TupleExprExpander> exprExpander;
[3c13c03]99                mutateAll( translationUnit, exprExpander );
100        }
101
[bf32bb8]102        namespace {
103                /// given a expression representing the member and an expression representing the aggregate,
104                /// reconstructs a flattened UntypedMemberExpr with the right precedence
[64ac636]105                Expression * reconstructMemberExpr( Expression * member, Expression * aggr, CodeLocation & loc ) {
[bf32bb8]106                        if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( member ) ) {
107                                // construct a new UntypedMemberExpr with the correct structure , and recursively
108                                // expand that member expression.
109                                MemberTupleExpander expander;
[64ac636]110                                UntypedMemberExpr * inner = new UntypedMemberExpr( memberExpr->get_aggregate(), aggr->clone() );
111                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member(), inner );
112                                inner->location = newMemberExpr->location = loc;
[bf32bb8]113                                memberExpr->set_member(nullptr);
114                                memberExpr->set_aggregate(nullptr);
115                                delete memberExpr;
116                                return newMemberExpr->acceptMutator( expander );
117                        } else {
118                                // not a member expression, so there is nothing to do but attach and return
[64ac636]119                                UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( member, aggr->clone() );
120                                newMemberExpr->location = loc;
121                                return newMemberExpr;
[bf32bb8]122                        }
123                }
124        }
125
126        Expression * MemberTupleExpander::mutate( UntypedMemberExpr * memberExpr ) {
[907eccb]127                if ( UntypedTupleExpr * tupleExpr = dynamic_cast< UntypedTupleExpr * > ( memberExpr->get_member() ) ) {
[141b786]128                        Expression * aggr = memberExpr->get_aggregate()->clone()->acceptMutator( *this );
129                        // aggregate expressions which might be impure must be wrapped in unique expressions
130                        // xxx - if there's a member-tuple expression nested in the aggregate, this currently generates the wrong code if a UniqueExpr is not used, and it's purely an optimization to remove the UniqueExpr
[9f10c4b8]131                        // if ( Tuples::maybeImpureIgnoreUnique( memberExpr->get_aggregate() ) ) aggr = new UniqueExpr( aggr );
[141b786]132                        aggr = new UniqueExpr( aggr );
[bf32bb8]133                        for ( Expression *& expr : tupleExpr->get_exprs() ) {
[64ac636]134                                expr = reconstructMemberExpr( expr, aggr, memberExpr->location );
135                                expr->location = memberExpr->location;
[bf32bb8]136                        }
[141b786]137                        delete aggr;
[64ac636]138                        tupleExpr->location = memberExpr->location;
[bf32bb8]139                        return tupleExpr;
140                } else {
[f0121d7]141                        // there may be a tuple expr buried in the aggregate
142                        // xxx - this is a memory leak
[64ac636]143                        UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->get_member()->clone(), memberExpr->get_aggregate()->acceptMutator( *this ) );
144                        newMemberExpr->location = memberExpr->location;
145                        return newMemberExpr;
[bf32bb8]146                }
147        }
148
[9f10c4b8]149        Expression * UniqueExprExpander::postmutate( UniqueExpr * unqExpr ) {
[141b786]150                const int id = unqExpr->get_id();
151
152                // on first time visiting a unique expr with a particular ID, generate the expression that replaces all UniqueExprs with that ID,
153                // and lookup on subsequent hits. This ensures that all unique exprs with the same ID reference the same variable.
154                if ( ! decls.count( id ) ) {
155                        Expression * assignUnq;
156                        Expression * var = unqExpr->get_var();
157                        if ( unqExpr->get_object() ) {
158                                // an object was generated to represent this unique expression -- it should be added to the list of declarations now
[9f10c4b8]159                                declsToAddBefore.push_back( unqExpr->get_object() );
[141b786]160                                unqExpr->set_object( nullptr );
161                                // steal the expr from the unqExpr
162                                assignUnq = UntypedExpr::createAssign( unqExpr->get_var()->clone(), unqExpr->get_expr() );
163                                unqExpr->set_expr( nullptr );
164                        } else {
165                                // steal the already generated assignment to var from the unqExpr - this has been generated by FixInit
166                                Expression * expr = unqExpr->get_expr();
167                                CommaExpr * commaExpr = safe_dynamic_cast< CommaExpr * >( expr );
168                                assignUnq = commaExpr->get_arg1();
169                                commaExpr->set_arg1( nullptr );
170                        }
[d56e5bc]171                        ObjectDecl * finished = new ObjectDecl( toString( "_unq", id, "_finished_" ), Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ),
[579263a]172                                                                                                        new SingleInit( new ConstantExpr( Constant::from_int( 0 ) ) ) );
[9f10c4b8]173                        declsToAddBefore.push_back( finished );
[141b786]174                        // (finished ? _unq_expr_N : (_unq_expr_N = <unqExpr->get_expr()>, finished = 1, _unq_expr_N))
175                        // This pattern ensures that each unique expression is evaluated once, regardless of evaluation order of the generated C code.
[d56e5bc]176                        Expression * assignFinished = UntypedExpr::createAssign( new VariableExpr(finished), new ConstantExpr( Constant::from_int( 1 ) ) );
[141b786]177                        ConditionalExpr * condExpr = new ConditionalExpr( new VariableExpr( finished ), var->clone(),
178                                new CommaExpr( new CommaExpr( assignUnq, assignFinished ), var->clone() ) );
179                        condExpr->set_result( var->get_result()->clone() );
[d5556a3]180                        condExpr->set_env( maybeClone( unqExpr->get_env() ) );
[141b786]181                        decls[id] = condExpr;
[3c13c03]182                }
[141b786]183                delete unqExpr;
184                return decls[id]->clone();
[6eb8948]185        }
186
[9f10c4b8]187        Expression * TupleAssignExpander::postmutate( TupleAssignExpr * assnExpr ) {
[d5556a3]188                StmtExpr * ret = assnExpr->get_stmtExpr();
189                assnExpr->set_stmtExpr( nullptr );
190                // move env to StmtExpr
191                ret->set_env( assnExpr->get_env() );
192                assnExpr->set_env( nullptr );
[3c13c03]193                delete assnExpr;
[d5556a3]194                return ret;
[6eb8948]195        }
196
[c92c09c]197        Type * TupleTypeReplacer::postmutate( TupleType * tupleType ) {
[e6512c8]198                unsigned tupleSize = tupleType->size();
199                if ( ! typeMap.count( tupleSize ) ) {
200                        // generate struct type to replace tuple type based on the number of components in the tuple
[94a8123]201                        StructDecl * decl = new StructDecl( toString( "_tuple", tupleSize, "_" ) );
[f006f01]202                        decl->set_body( true );
[e6512c8]203                        for ( size_t i = 0; i < tupleSize; ++i ) {
[c92c09c]204                                TypeDecl * tyParam = new TypeDecl( toString( "tuple_param_", tupleSize, "_", i ), Type::StorageClasses(), nullptr, TypeDecl::Any );
[68fe077a]205                                decl->get_members().push_back( new ObjectDecl( toString("field_", i ), Type::StorageClasses(), LinkageSpec::C, nullptr, new TypeInstType( Type::Qualifiers(), tyParam->get_name(), tyParam ), nullptr ) );
[d9fa60a]206                                decl->get_parameters().push_back( tyParam );
[f006f01]207                        }
[e6512c8]208                        if ( tupleSize == 0 ) {
[4c8621ac]209                                // empty structs are not standard C. Add a dummy field to empty tuples to silence warnings when a compound literal Tuple0 is created.
[68fe077a]210                                decl->get_members().push_back( new ObjectDecl( "dummy", Type::StorageClasses(), LinkageSpec::C, nullptr, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), nullptr ) );
[4c8621ac]211                        }
[e6512c8]212                        typeMap[tupleSize] = decl;
[c92c09c]213                        declsToAddBefore.push_back( decl );
[f006f01]214                }
[d9fa60a]215                Type::Qualifiers qualifiers = tupleType->get_qualifiers();
216
[e6512c8]217                StructDecl * decl = typeMap[tupleSize];
[d9fa60a]218                StructInstType * newType = new StructInstType( qualifiers, decl );
[c92c09c]219                for ( auto p : group_iterate( tupleType->get_types(), decl->get_parameters() ) ) {
220                        Type * t = std::get<0>(p);
[d9fa60a]221                        newType->get_parameters().push_back( new TypeExpr( t->clone() ) );
222                }
223                delete tupleType;
224                return newType;
[f006f01]225        }
226
[ab904dc]227        Expression * TupleIndexExpander::postmutate( TupleIndexExpr * tupleExpr ) {
228                Expression * tuple = tupleExpr->get_tuple();
[3c13c03]229                assert( tuple );
230                tupleExpr->set_tuple( nullptr );
231                unsigned int idx = tupleExpr->get_index();
[d5556a3]232                TypeSubstitution * env = tupleExpr->get_env();
233                tupleExpr->set_env( nullptr );
[3c13c03]234                delete tupleExpr;
235
236                StructInstType * type = safe_dynamic_cast< StructInstType * >( tuple->get_result() );
237                StructDecl * structDecl = type->get_baseStruct();
238                assert( structDecl->get_members().size() > idx );
239                Declaration * member = *std::next(structDecl->get_members().begin(), idx);
[d5556a3]240                MemberExpr * memExpr = new MemberExpr( safe_dynamic_cast< DeclarationWithType * >( member ), tuple );
241                memExpr->set_env( env );
242                return memExpr;
[3c13c03]243        }
244
[d5556a3]245        Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs, TypeSubstitution * env ) {
[65660bd]246                if ( result->isVoid() ) {
247                        // void result - don't need to produce a value for cascading - just output a chain of comma exprs
248                        assert( ! exprs.empty() );
249                        std::list< Expression * >::const_iterator iter = exprs.begin();
[d5556a3]250                        Expression * expr = new CastExpr( *iter++ );
[65660bd]251                        for ( ; iter != exprs.end(); ++iter ) {
[d5556a3]252                                expr = new CommaExpr( expr, new CastExpr( *iter ) );
[65660bd]253                        }
[d5556a3]254                        expr->set_env( env );
[65660bd]255                        return expr;
256                } else {
257                        // typed tuple expression - produce a compound literal which performs each of the expressions
258                        // as a distinct part of its initializer - the produced compound literal may be used as part of
259                        // another expression
260                        std::list< Initializer * > inits;
261                        for ( Expression * expr : exprs ) {
262                                inits.push_back( new SingleInit( expr ) );
263                        }
[d5556a3]264                        Expression * expr = new CompoundLiteralExpr( result, new ListInit( inits ) );
265                        expr->set_env( env );
266                        return expr;
[3c13c03]267                }
268        }
269
[9f10c4b8]270        Expression * TupleExprExpander::postmutate( TupleExpr * tupleExpr ) {
[65660bd]271                Type * result = tupleExpr->get_result();
272                std::list< Expression * > exprs = tupleExpr->get_exprs();
273                assert( result );
[d5556a3]274                TypeSubstitution * env = tupleExpr->get_env();
[65660bd]275
[bf32bb8]276                // remove data from shell and delete it
[65660bd]277                tupleExpr->set_result( nullptr );
278                tupleExpr->get_exprs().clear();
[d5556a3]279                tupleExpr->set_env( nullptr );
[65660bd]280                delete tupleExpr;
281
[d5556a3]282                return replaceTupleExpr( result, exprs, env );
[65660bd]283        }
284
285        Type * makeTupleType( const std::list< Expression * > & exprs ) {
286                // produce the TupleType which aggregates the types of the exprs
[62423350]287                std::list< Type * > types;
288                Type::Qualifiers qualifiers( Type::Const | Type::Volatile | Type::Restrict | Type::Lvalue | Type::Atomic | Type::Mutex );
[3c13c03]289                for ( Expression * expr : exprs ) {
290                        assert( expr->get_result() );
[65660bd]291                        if ( expr->get_result()->isVoid() ) {
292                                // if the type of any expr is void, the type of the entire tuple is void
293                                return new VoidType( Type::Qualifiers() );
294                        }
[3c13c03]295                        Type * type = expr->get_result()->clone();
[62423350]296                        types.push_back( type );
[65660bd]297                        // the qualifiers on the tuple type are the qualifiers that exist on all component types
[3c13c03]298                        qualifiers &= type->get_qualifiers();
299                } // for
[907eccb]300                if ( exprs.empty() ) qualifiers = Type::Qualifiers();
[62423350]301                return new TupleType( qualifiers, types );
[3c13c03]302        }
[65660bd]303
[8bf784a]304        TypeInstType * isTtype( Type * type ) {
305                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( type ) ) {
[0b150ec]306                        if ( inst->get_baseType() && inst->get_baseType()->get_kind() == TypeDecl::Ttype ) {
[8bf784a]307                                return inst;
308                        }
309                }
310                return nullptr;
311        }
312
[65660bd]313        namespace {
314                /// determines if impurity (read: side-effects) may exist in a piece of code. Currently gives a very crude approximation, wherein any function call expression means the code may be impure
315                class ImpurityDetector : public Visitor {
316                public:
[9f10c4b8]317                        ImpurityDetector( bool ignoreUnique ) : ignoreUnique( ignoreUnique ) {}
318
[65660bd]319                        typedef Visitor Parent;
[b7b8674]320                        virtual void visit( ApplicationExpr * appExpr ) {
321                                if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
322                                        if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
323                                                if ( function->get_name() == "*?" || function->get_name() == "?[?]" ) {
324                                                        // intrinsic dereference, subscript are pure, but need to recursively look for impurity
325                                                        Parent::visit( appExpr );
326                                                        return;
327                                                }
328                                        }
329                                }
330                                maybeImpure = true;
331                        }
[9f10c4b8]332                        virtual void visit( UntypedExpr * ) { maybeImpure = true; }
333                        virtual void visit( UniqueExpr * unq ) {
334                                if ( ignoreUnique ) {
335                                        // bottom out at unique expression.
336                                        // The existence of a unique expression doesn't change the purity of an expression.
337                                        // That is, even if the wrapped expression is impure, the wrapper protects the rest of the expression.
338                                        return;
339                                }
340                                maybeAccept( unq->expr, *this );
341                        }
342
[65660bd]343                        bool maybeImpure = false;
[9f10c4b8]344                        bool ignoreUnique;
[65660bd]345                };
346        } // namespace
347
348        bool maybeImpure( Expression * expr ) {
[9f10c4b8]349                ImpurityDetector detector( false );
350                expr->accept( detector );
351                return detector.maybeImpure;
352        }
353
354        bool maybeImpureIgnoreUnique( Expression * expr ) {
355                ImpurityDetector detector( true );
[65660bd]356                expr->accept( detector );
357                return detector.maybeImpure;
358        }
[6eb8948]359} // namespace Tuples
360
361// Local Variables: //
362// tab-width: 4 //
363// mode: c++ //
364// compile-command: "make install" //
365// End: //
Note: See TracBrowser for help on using the repository browser.