source: src/Tuples/TupleExpansion.cc @ 0588d8c

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 0588d8c was 0588d8c, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Stubbed a few routines for later to help compilation

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