source: src/Tuples/TupleExpansion.cc @ a2f146ee

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprno_listpersistent-indexerpthread-emulationqualifiedEnum
Last change on this file since a2f146ee was aee472e, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Reduce the number of unnecessary temporaries generated for member tuple expressions, reduce pure (no side-effect) tuple index expressions to the relevant component expression

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