source: src/Tuples/TupleAssignment.cc @ b3b2077

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

refactor some code that generates dereference and assignment calls

  • Property mode set to 100644
File size: 9.9 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 : Rob Schluntz
12// Last Modified On : Wed Nov 9 13:48:42 2016
13// Update Count     : 2
14//
15
16#include "ResolvExpr/AlternativeFinder.h"
17#include "ResolvExpr/Alternative.h"
18#include "ResolvExpr/typeops.h"
19#include "SynTree/Expression.h"
20#include "SynTree/Initializer.h"
21#include "Tuples.h"
22#include "Common/SemanticError.h"
23#include "InitTweak/InitTweak.h"
24
25#include <functional>
26#include <algorithm>
27#include <iterator>
28#include <iostream>
29#include <cassert>
30#include <set>
31#include <unordered_set>
32
33namespace Tuples {
34        class TupleAssignSpotter {
35          public:
36                // dispatcher for Tuple (multiple and mass) assignment operations
37                TupleAssignSpotter( ResolvExpr::AlternativeFinder & );
38                void spot( UntypedExpr * expr, const std::list<ResolvExpr::AltList> &possibilities );
39
40          private:
41                void match();
42
43                struct Matcher {
44                  public:
45                        Matcher( TupleAssignSpotter &spotter, const ResolvExpr::AltList & alts );
46                        virtual ~Matcher() {}
47                        virtual void match( std::list< Expression * > &out ) = 0;
48                        ResolvExpr::AltList lhs, rhs;
49                        TupleAssignSpotter &spotter;
50                        std::list< ObjectDecl * > tmpDecls;
51                };
52
53                struct MassAssignMatcher : public Matcher {
54                  public:
55                        MassAssignMatcher( TupleAssignSpotter &spotter, const ResolvExpr::AltList & alts );
56                        virtual void match( std::list< Expression * > &out );
57                };
58
59                struct MultipleAssignMatcher : public Matcher {
60                  public:
61                        MultipleAssignMatcher( TupleAssignSpotter &spot, const ResolvExpr::AltList & alts );
62                        virtual void match( std::list< Expression * > &out );
63                };
64
65                ResolvExpr::AlternativeFinder &currentFinder;
66                std::string fname;
67                std::unique_ptr< Matcher > matcher;
68        };
69
70        /// true if expr is an expression of tuple type, i.e. a tuple expression, tuple variable, or MRV (multiple-return-value) function
71        bool isTuple( Expression *expr ) {
72                if ( ! expr ) return false;
73                assert( expr->has_result() );
74                return dynamic_cast<TupleExpr *>(expr) || expr->get_result()->size() > 1;
75        }
76
77        template< typename AltIter >
78        bool isMultAssign( AltIter begin, AltIter end ) {
79                // multiple assignment if more than one alternative in the range or if
80                // the alternative is a tuple
81                if ( begin == end ) return false;
82                if ( isTuple( begin->expr ) ) return true;
83                return ++begin != end;
84        }
85
86        bool pointsToTuple( Expression *expr ) {
87                // also check for function returning tuple of reference types
88                if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
89                        return pointsToTuple( castExpr->get_arg() );
90                } else if ( AddressExpr *addr = dynamic_cast< AddressExpr * >( expr) ) {
91                        return isTuple( addr->get_arg() );
92                }
93                return false;
94        }
95
96        void handleTupleAssignment( ResolvExpr::AlternativeFinder & currentFinder, UntypedExpr * expr, const std::list<ResolvExpr::AltList> &possibilities ) {
97                TupleAssignSpotter spotter( currentFinder );
98                spotter.spot( expr, possibilities );
99        }
100
101        TupleAssignSpotter::TupleAssignSpotter( ResolvExpr::AlternativeFinder &f )
102                : currentFinder(f) {}
103
104        void TupleAssignSpotter::spot( UntypedExpr * expr, const std::list<ResolvExpr::AltList> &possibilities ) {
105                if (  NameExpr *op = dynamic_cast< NameExpr * >(expr->get_function()) ) {
106                        if ( InitTweak::isCtorDtorAssign( op->get_name() ) ) {
107                                fname = op->get_name();
108                                for ( std::list<ResolvExpr::AltList>::const_iterator ali = possibilities.begin(); ali != possibilities.end(); ++ali ) {
109                                        if ( ali->size() == 0 ) continue; // AlternativeFinder will natrually handle this case, if it's legal
110                                        if ( ali->size() <= 1 && InitTweak::isAssignment( op->get_name() ) ) {
111                                                // what does it mean if an assignment takes 1 argument? maybe someone defined such a function, in which case AlternativeFinder will naturally handle it
112                                                continue;
113                                        }
114
115                                        assert( ! ali->empty() );
116                                        // grab args 2-N and group into a TupleExpr
117                                        const ResolvExpr::Alternative & alt1 = ali->front();
118                                        auto begin = std::next(ali->begin(), 1), end = ali->end();
119                                        if ( pointsToTuple(alt1.expr) ) {
120                                                if ( isMultAssign( begin, end ) ) {
121                                                        matcher.reset( new MultipleAssignMatcher( *this, *ali ) );
122                                                } else {
123                                                        // mass assignment
124                                                        matcher.reset( new MassAssignMatcher( *this,  *ali ) );
125                                                }
126                                                match();
127                                        }
128                                }
129                        }
130                }
131        }
132
133        void TupleAssignSpotter::match() {
134                assert ( matcher != 0 );
135
136                std::list< Expression * > new_assigns;
137                matcher->match( new_assigns );
138
139                if ( new_assigns.empty() ) return;
140                ResolvExpr::AltList current;
141                // now resolve new assignments
142                for ( std::list< Expression * >::iterator i = new_assigns.begin(); i != new_assigns.end(); ++i ) {
143                        ResolvExpr::AlternativeFinder finder( currentFinder.get_indexer(), currentFinder.get_environ() );
144                        try {
145                                finder.findWithAdjustment(*i);
146                        } catch (...) {
147                                return; // xxx - no match should not mean failure, it just means this particular tuple assignment isn't valid
148                        }
149                        // prune expressions that don't coincide with
150                        ResolvExpr::AltList alts = finder.get_alternatives();
151                        assert( alts.size() == 1 );
152                        assert( alts.front().expr != 0 );
153                        current.push_back( alts.front() );
154                }
155
156                // extract expressions from the assignment alternatives to produce a list of assignments that
157                // together form a single alternative
158                std::list< Expression *> solved_assigns;
159                for ( ResolvExpr::Alternative & alt : current ) {
160                        solved_assigns.push_back( alt.expr->clone() );
161                }
162                // xxx - need to do this??
163                ResolvExpr::TypeEnvironment compositeEnv;
164                simpleCombineEnvironments( current.begin(), current.end(), compositeEnv );
165                currentFinder.get_alternatives().push_front( ResolvExpr::Alternative(new TupleAssignExpr(solved_assigns, matcher->tmpDecls), compositeEnv, ResolvExpr::sumCost( current ) ) );
166        }
167
168        TupleAssignSpotter::Matcher::Matcher( TupleAssignSpotter &spotter, const ResolvExpr::AltList &alts ) : spotter(spotter) {
169                assert( ! alts.empty() );
170                ResolvExpr::Alternative lhsAlt = alts.front();
171                // peel off the cast that exists on ctor/dtor expressions
172                bool isCast = false;
173                if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( lhsAlt.expr ) ) {
174                        lhsAlt.expr = castExpr->get_arg();
175                        castExpr->set_arg( nullptr );
176                        delete castExpr;
177                        isCast = true;
178                }
179
180                // explode the lhs so that each field of the tuple-valued-expr is assigned.
181                explode( lhsAlt, spotter.currentFinder.get_indexer(), back_inserter(lhs) );
182
183                // and finally, re-add the cast to each lhs expr, so that qualified tuple fields can be constructed
184                if ( isCast ) {
185                        for ( ResolvExpr::Alternative & alt : lhs ) {
186                                Expression *& expr = alt.expr;
187                                Type * castType = expr->get_result()->clone();
188                                Type * type = InitTweak::getPointerBase( castType );
189                                assert( type );
190                                type->get_qualifiers() -= Type::Qualifiers(true, true, true, false, true, true);
191                                type->set_isLvalue( true ); // xxx - might not need this
192                                expr = new CastExpr( expr, castType );
193                        }
194                }
195        }
196
197        TupleAssignSpotter::MassAssignMatcher::MassAssignMatcher( TupleAssignSpotter &spotter, const ResolvExpr::AltList & alts ) : Matcher( spotter, alts ) {
198                assert( alts.size() == 1 || alts.size() == 2 );
199                if ( alts.size() == 2 ) {
200                        rhs.push_back( alts.back() );
201                }
202        }
203
204        TupleAssignSpotter::MultipleAssignMatcher::MultipleAssignMatcher( TupleAssignSpotter &spotter, const ResolvExpr::AltList & alts ) : Matcher( spotter, alts ) {
205                // explode the rhs so that each field of the tuple-valued-expr is assigned.
206                explode( std::next(alts.begin(), 1), alts.end(), spotter.currentFinder.get_indexer(), back_inserter(rhs) );
207        }
208
209        UntypedExpr * createFunc( const std::string &fname, ObjectDecl *left, ObjectDecl *right ) {
210                assert( left );
211                std::list< Expression * > args;
212                args.push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( left ) ) ) );
213                // args.push_back( new AddressExpr( new VariableExpr( left ) ) );
214                if ( right ) args.push_back( new VariableExpr( right ) );
215                return new UntypedExpr( new NameExpr( fname ), args );
216        }
217
218        ObjectDecl * newObject( UniqueName & namer, Expression * expr ) {
219                assert( expr->has_result() && ! expr->get_result()->isVoid() );
220                return new ObjectDecl( namer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, nullptr, expr->get_result()->clone(), new SingleInit( expr->clone() ) );
221        }
222
223        void TupleAssignSpotter::MassAssignMatcher::match( std::list< Expression * > &out ) {
224                static UniqueName lhsNamer( "__massassign_L" );
225                static UniqueName rhsNamer( "__massassign_R" );
226                assert ( ! lhs.empty() && rhs.size() <= 1);
227
228                ObjectDecl * rtmp = rhs.size() == 1 ? newObject( rhsNamer, rhs.front().expr ) : nullptr;
229                for ( ResolvExpr::Alternative & lhsAlt : lhs ) {
230                        ObjectDecl * ltmp = newObject( lhsNamer, lhsAlt.expr );
231                        out.push_back( createFunc( spotter.fname, ltmp, rtmp ) );
232                        tmpDecls.push_back( ltmp );
233                }
234                if ( rtmp ) tmpDecls.push_back( rtmp );
235        }
236
237        void TupleAssignSpotter::MultipleAssignMatcher::match( std::list< Expression * > &out ) {
238                static UniqueName lhsNamer( "__multassign_L" );
239                static UniqueName rhsNamer( "__multassign_R" );
240
241                // xxx - need more complicated matching?
242                if ( lhs.size() == rhs.size() ) {
243                        std::list< ObjectDecl * > ltmp;
244                        std::list< ObjectDecl * > rtmp;
245                        std::transform( lhs.begin(), lhs.end(), back_inserter( ltmp ), []( ResolvExpr::Alternative & alt ){
246                                return newObject( lhsNamer, alt.expr );
247                        });
248                        std::transform( rhs.begin(), rhs.end(), back_inserter( rtmp ), []( ResolvExpr::Alternative & alt ){
249                                return newObject( rhsNamer, alt.expr );
250                        });
251                        zipWith( ltmp.begin(), ltmp.end(), rtmp.begin(), rtmp.end(), back_inserter(out), [&](ObjectDecl * obj1, ObjectDecl * obj2 ) { return createFunc(spotter.fname, obj1, obj2); } );
252                        tmpDecls.splice( tmpDecls.end(), ltmp );
253                        tmpDecls.splice( tmpDecls.end(), rtmp );
254                }
255        }
256} // namespace Tuples
257
258// Local Variables: //
259// tab-width: 4 //
260// mode: c++ //
261// compile-command: "make install" //
262// End: //
Note: See TracBrowser for help on using the repository browser.