source: src/Tuples/TupleExpansion.cc @ cbce272

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

Add tuple parameter bindings to type substitution

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