source: src/Tuples/TupleExpansion.cc @ f6582243

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

Fix member expressions in the InstantiateGeneric? pass so that they correctly refer to the member from the instantiation

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