source: src/GenPoly/Lvalue.cc @ 1a4bef3

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

Ensure that dereference type is marked as lvalue after reference conversion [fixes #74]

  • Property mode set to 100644
File size: 19.4 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// Lvalue.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Mar 17 09:11:18 2017
13// Update Count     : 5
14//
15
16#include <cassert>                       // for strict_dynamic_cast
17#include <string>                        // for string
18
19#include "Common/PassVisitor.h"
20#include "Common/SemanticError.h"        // for SemanticError
21#include "GenPoly.h"                     // for isPolyType
22#include "Lvalue.h"
23
24#include "Parser/LinkageSpec.h"          // for Spec, isBuiltin, Intrinsic
25#include "ResolvExpr/TypeEnvironment.h"  // for AssertionSet, OpenVarSet
26#include "ResolvExpr/Unify.h"            // for unify
27#include "ResolvExpr/typeops.h"
28#include "SymTab/Autogen.h"
29#include "SymTab/Indexer.h"              // for Indexer
30#include "SynTree/Declaration.h"         // for Declaration, FunctionDecl
31#include "SynTree/Expression.h"          // for Expression, ConditionalExpr
32#include "SynTree/Mutator.h"             // for mutateAll, Mutator
33#include "SynTree/Statement.h"           // for ReturnStmt, Statement (ptr o...
34#include "SynTree/Type.h"                // for PointerType, Type, FunctionType
35#include "SynTree/Visitor.h"             // for Visitor, acceptAll
36
37#if 0
38#define PRINT(x) x
39#else
40#define PRINT(x)
41#endif
42
43namespace GenPoly {
44        namespace {
45                // TODO: fold this into the general createDeref function??
46                Expression * mkDeref( Expression * arg ) {
47                        if ( SymTab::dereferenceOperator ) {
48                                VariableExpr * deref = new VariableExpr( SymTab::dereferenceOperator );
49                                deref->result = new PointerType( Type::Qualifiers(), deref->result );
50                                Type * base = InitTweak::getPointerBase( arg->result );
51                                assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->result ).c_str() );
52                                ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
53                                delete ret->result;
54                                ret->result = base->clone();
55                                ret->result->set_lvalue( true );
56                                return ret;
57                        } else {
58                                return UntypedExpr::createDeref( arg );
59                        }
60                }
61
62                struct ReferenceConversions final {
63                        Expression * postmutate( CastExpr * castExpr );
64                        Expression * postmutate( AddressExpr * addrExpr );
65                };
66
67                /// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
68                struct FixIntrinsicArgs final {
69                        Expression * postmutate( ApplicationExpr * appExpr );
70                };
71
72                struct FixIntrinsicResult final : public WithGuards {
73                        Expression * postmutate( ApplicationExpr * appExpr );
74                        void premutate( FunctionDecl * funcDecl );
75                        bool inIntrinsic = false;
76                };
77
78                /// Replace reference types with pointer types
79                struct ReferenceTypeElimination final {
80                        Type * postmutate( ReferenceType * refType );
81                };
82
83                /// GCC-like Generalized Lvalues (which have since been removed from GCC)
84                /// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
85                /// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
86                struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
87                        Expression * postmutate( AddressExpr * addressExpr );
88                        Expression * postmutate( MemberExpr * memExpr );
89
90                        template<typename Func>
91                        Expression * applyTransformation( Expression * expr, Expression * arg, Func mkExpr );
92                };
93
94                /// Removes redundant &*/*& pattern that this pass can generate
95                struct CollapseAddrDeref final {
96                        Expression * postmutate( AddressExpr * addressExpr );
97                        Expression * postmutate( ApplicationExpr * appExpr );
98                };
99
100                struct AddrRef final : public WithGuards {
101                        void premutate( AddressExpr * addrExpr );
102                        Expression * postmutate( AddressExpr * addrExpr );
103                        void premutate( Expression * expr );
104
105                        bool first = true;
106                        bool current = false;
107                        int refDepth = 0;
108                };
109        } // namespace
110
111        static bool referencesEliminated = false;
112        // used by UntypedExpr::createDeref to determine whether result type of dereference should be ReferenceType or value type.
113        bool referencesPermissable() {
114                return ! referencesEliminated;
115        }
116
117        void convertLvalue( std::list< Declaration* >& translationUnit ) {
118                PassVisitor<ReferenceConversions> refCvt;
119                PassVisitor<ReferenceTypeElimination> elim;
120                PassVisitor<GeneralizedLvalue> genLval;
121                PassVisitor<FixIntrinsicArgs> fixer;
122                PassVisitor<CollapseAddrDeref> collapser;
123                PassVisitor<AddrRef> addrRef;
124                PassVisitor<FixIntrinsicResult> intrinsicResults;
125                mutateAll( translationUnit, intrinsicResults );
126                mutateAll( translationUnit, addrRef );
127                mutateAll( translationUnit, refCvt );
128                mutateAll( translationUnit, fixer );
129                mutateAll( translationUnit, collapser );
130                mutateAll( translationUnit, genLval );
131                mutateAll( translationUnit, elim );  // last because other passes need reference types to work
132
133                // from this point forward, no other pass should create reference types.
134                referencesEliminated = true;
135        }
136
137        Expression * generalizedLvalue( Expression * expr ) {
138                PassVisitor<GeneralizedLvalue> genLval;
139                return expr->acceptMutator( genLval );
140        }
141
142        namespace {
143                // true for intrinsic function calls that return a reference
144                bool isIntrinsicReference( Expression * expr ) {
145                        if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
146                                std::string fname = InitTweak::getFunctionName( untyped );
147                                // known intrinsic-reference prelude functions
148                                return fname == "*?" || fname == "?[?]";
149                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
150                                if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
151                                        // use type of return variable rather than expr result type, since it may have been changed to a pointer type
152                                        FunctionType * ftype = GenPoly::getFunctionType( func->get_type() );
153                                        Type * ret = ftype->get_returnVals().empty() ? nullptr : ftype->get_returnVals().front()->get_type();
154                                        return func->get_linkage() == LinkageSpec::Intrinsic && dynamic_cast<ReferenceType *>( ret );
155                                }
156                        }
157                        return false;
158                }
159
160                Expression * FixIntrinsicResult::postmutate( ApplicationExpr * appExpr ) {
161                        if ( isIntrinsicReference( appExpr ) ) {
162                                // eliminate reference types from intrinsic applications - now they return lvalues
163                                Type * result = appExpr->get_result();
164                                appExpr->set_result( result->stripReferences()->clone() );
165                                appExpr->get_result()->set_lvalue( true );
166                                if ( ! inIntrinsic ) {
167                                        // when not in an intrinsic function, add a cast to
168                                        // don't add cast when in an intrinsic function, since they already have the cast
169                                        Expression * ret = new CastExpr( appExpr, result );
170                                        ret->set_env( appExpr->get_env() );
171                                        appExpr->set_env( nullptr );
172                                        return ret;
173                                }
174                                delete result;
175                        }
176                        return appExpr;
177                }
178
179                void FixIntrinsicResult::premutate( FunctionDecl * funcDecl ) {
180                        GuardValue( inIntrinsic );
181                        inIntrinsic =  funcDecl->linkage == LinkageSpec::Intrinsic;
182                }
183
184                Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
185                        // intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
186                        if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
187                                FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
188                                assertf( ftype, "Function declaration does not have function type." );
189                                // can be of differing lengths only when function is variadic
190                                assertf( ftype->get_parameters().size() == appExpr->get_args().size() || ftype->get_isVarArgs(), "ApplicationExpr args do not match formal parameter type." );
191
192
193                                unsigned int i = 0;
194                                const unsigned int end = ftype->get_parameters().size();
195                                for ( auto p : unsafe_group_iterate( appExpr->get_args(), ftype->get_parameters() ) ) {
196                                        if (i == end) break;
197                                        Expression *& arg = std::get<0>( p );
198                                        Type * formal = std::get<1>( p )->get_type();
199                                        PRINT(
200                                                std::cerr << "pair<0>: " << arg << std::endl;
201                                                std::cerr << "pair<1>: " << formal << std::endl;
202                                        )
203                                        if ( dynamic_cast<ReferenceType*>( formal ) ) {
204                                                if ( isIntrinsicReference( arg ) ) { // do not combine conditions, because that changes the meaning of the else if
205                                                        if ( function->get_linkage() != LinkageSpec::Intrinsic ) { // intrinsic functions that turn pointers into references
206                                                                // if argument is dereference or array subscript, the result isn't REALLY a reference, so it's not necessary to fix the argument
207                                                                PRINT(
208                                                                        std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
209                                                                )
210                                                                arg = new AddressExpr( arg );
211                                                        }
212                                                } else if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
213                                                        // std::cerr << "===adding deref to arg" << std::endl;
214                                                        // if the parameter is a reference, add a dereference to the reference-typed argument.
215                                                        Type * baseType = InitTweak::getPointerBase( arg->get_result() );
216                                                        assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->get_result() ).c_str() );
217                                                        PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
218                                                        delete arg->get_result();
219                                                        arg->set_result( ptrType );
220                                                        arg = mkDeref( arg );
221                                                }
222                                        }
223                                        ++i;
224                                }
225                        }
226                        return appExpr;
227                }
228
229                // idea: &&&E: get outer &, inner &
230                // at inner &, record depth D of reference type
231                // at outer &, add D derefs.
232                void AddrRef::premutate( Expression * ) {
233                        GuardValue( current );
234                        GuardValue( first );
235                        current = false;
236                        first = true;
237                }
238
239                void AddrRef::premutate( AddressExpr * ) {
240                        GuardValue( current );
241                        GuardValue( first );
242                        current = first;
243                        first = false;
244                        if ( current ) {
245                                GuardValue( refDepth );
246                                refDepth = 0;
247                        }
248                }
249
250                Expression * AddrRef::postmutate( AddressExpr * addrExpr ) {
251                        if ( refDepth == 0 ) {
252                                if ( ! isIntrinsicReference( addrExpr->get_arg() ) ) {
253                                        // try to avoid ?[?]
254                                        refDepth = addrExpr->get_arg()->get_result()->referenceDepth();
255                                }
256                        }
257                        if ( current ) {
258                                Expression * ret = addrExpr;
259                                while ( refDepth ) {
260                                        ret = mkDeref( ret );
261                                        refDepth--;
262                                }
263                                return ret;
264                        }
265                        return addrExpr;
266                }
267
268                Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
269                        // Inner expression may have been lvalue to reference conversion, which becomes an address expression.
270                        // In this case, remove the outer address expression and return the argument.
271                        // TODO: It's possible that this might catch too much and require a more sophisticated check.
272                        return addrExpr;
273                }
274
275                Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
276                        // xxx - is it possible to convert directly between reference types with a different base? E.g.,
277                        //   int x;
278                        //   (double&)x;
279                        // At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
280                        // after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
281                        // pointer casts in the right places.
282
283                        // conversion to reference type
284                        if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->get_result() ) ) {
285                                (void)refType;
286                                if ( ReferenceType * otherRef = dynamic_cast< ReferenceType * >( castExpr->get_arg()->get_result() ) ) {
287                                        // nothing to do if casting from reference to reference.
288                                        (void)otherRef;
289                                        PRINT( std::cerr << "convert reference to reference -- nop" << std::endl; )
290                                        if ( isIntrinsicReference( castExpr->get_arg() ) ) {
291                                                Expression * callExpr = castExpr->get_arg();
292                                                PRINT(
293                                                        std::cerr << "but arg is deref -- &" << std::endl;
294                                                        std::cerr << callExpr << std::endl;
295                                                )
296                                                callExpr = new AddressExpr( callExpr ); // this doesn't work properly for multiple casts
297                                                delete callExpr->get_result();
298                                                callExpr->set_result( refType->clone() );
299                                                // move environment out to new top-level
300                                                callExpr->set_env( castExpr->get_env() );
301                                                castExpr->set_arg( nullptr );
302                                                castExpr->set_env( nullptr );
303                                                delete castExpr;
304                                                return callExpr;
305                                        }
306                                        int depth1 = refType->referenceDepth();
307                                        int depth2 = otherRef->referenceDepth();
308                                        int diff = depth1-depth2;
309                                        if ( diff == 0 ) {
310                                                // conversion between references of the same depth
311                                                assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
312                                                PRINT( std::cerr << castExpr << std::endl; )
313                                                return castExpr;
314                                        } else if ( diff < 0 ) {
315                                                // conversion from reference to reference with less depth (e.g. int && -> int &): add dereferences
316                                                Expression * ret = castExpr->arg;
317                                                for ( int i = 0; i < diff; ++i ) {
318                                                        ret = mkDeref( ret );
319                                                }
320                                                ret->env = castExpr->env;
321                                                delete ret->result;
322                                                ret->result = castExpr->result;
323                                                ret->result->set_lvalue( true ); // ensure result is lvalue
324                                                castExpr->env = nullptr;
325                                                castExpr->arg = nullptr;
326                                                castExpr->result = nullptr;
327                                                delete castExpr;
328                                                return ret;
329                                        } else if ( diff > 0 ) {
330                                                // conversion from reference to reference with more depth (e.g. int & -> int &&): add address-of
331                                                Expression * ret = castExpr->arg;
332                                                for ( int i = 0; i < diff; ++i ) {
333                                                        ret = new AddressExpr( ret );
334                                                }
335                                                ret->env = castExpr->env;
336                                                delete ret->result;
337                                                ret->result = castExpr->result;
338                                                castExpr->env = nullptr;
339                                                castExpr->arg = nullptr;
340                                                castExpr->result = nullptr;
341                                                delete castExpr;
342                                                return ret;
343                                        }
344
345                                        assertf( depth1 == depth2, "non-intrinsic reference with cast of reference to reference not yet supported: %d %d %s", depth1, depth2, toString( castExpr ).c_str() );
346                                        PRINT( std::cerr << castExpr << std::endl; )
347                                        return castExpr;
348                                } else if ( castExpr->arg->result->get_lvalue() ) {
349                                        // conversion from lvalue to reference
350                                        // xxx - keep cast, but turn into pointer cast??
351                                        // xxx - memory
352                                        PRINT(
353                                                std::cerr << "convert lvalue to reference -- &" << std::endl;
354                                                std::cerr << castExpr->arg << std::endl;
355                                        )
356                                        AddressExpr * ret = new AddressExpr( castExpr->arg );
357                                        if ( refType->base->get_qualifiers() != castExpr->arg->result->get_qualifiers() ) {
358                                                // must keep cast if cast-to type is different from the actual type
359                                                castExpr->arg = ret;
360                                                return castExpr;
361                                        }
362                                        ret->env = castExpr->env;
363                                        delete ret->result;
364                                        ret->result = castExpr->result;
365                                        castExpr->env = nullptr;
366                                        castExpr->arg = nullptr;
367                                        castExpr->result = nullptr;
368                                        delete castExpr;
369                                        return ret;
370                                } else {
371                                        // rvalue to reference conversion -- introduce temporary
372                                }
373                                assertf( false, "Only conversions to reference from lvalue are currently supported: %s", toString( castExpr ).c_str() );
374                        } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( castExpr->arg->result ) ) {
375                                (void)refType;
376                                // conversion from reference to rvalue
377                                PRINT(
378                                        std::cerr << "convert reference to rvalue -- *" << std::endl;
379                                        std::cerr << "was = " << castExpr << std::endl;
380                                )
381                                Expression * ret = castExpr->arg;
382                                TypeSubstitution * env = castExpr->env;
383                                castExpr->set_env( nullptr );
384                                if ( ! isIntrinsicReference( ret ) ) {
385                                        // dereference if not already dereferenced
386                                        ret = mkDeref( ret );
387                                }
388                                if ( ResolvExpr::typesCompatibleIgnoreQualifiers( castExpr->result, castExpr->arg->result->stripReferences(), SymTab::Indexer() ) ) {
389                                        // can remove cast if types are compatible, changing expression type to value type
390                                        ret->result = castExpr->result->clone();
391                                        ret->result->set_lvalue( true );  // ensure result is lvalue
392                                        castExpr->arg = nullptr;
393                                        delete castExpr;
394                                } else {
395                                        // must keep cast if types are different
396                                        castExpr->arg = ret;
397                                        ret = castExpr;
398                                }
399                                ret->set_env( env );
400                                PRINT( std::cerr << "now: " << ret << std::endl; )
401                                return ret;
402                        }
403                        return castExpr;
404                }
405
406                Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
407                        Type * base = refType->get_base();
408                        Type::Qualifiers qualifiers = refType->get_qualifiers();
409                        refType->set_base( nullptr );
410                        delete refType;
411                        return new PointerType( qualifiers, base );
412                }
413
414                template<typename Func>
415                Expression * GeneralizedLvalue::applyTransformation( Expression * expr, Expression * arg, Func mkExpr ) {
416                        if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( arg ) ) {
417                                Expression * arg1 = commaExpr->get_arg1()->clone();
418                                Expression * arg2 = commaExpr->get_arg2()->clone();
419                                Expression * ret = new CommaExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ) );
420                                ret->set_env( expr->get_env() );
421                                expr->set_env( nullptr );
422                                delete expr;
423                                return ret;
424                        } else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( arg ) ) {
425                                Expression * arg1 = condExpr->get_arg1()->clone();
426                                Expression * arg2 = condExpr->get_arg2()->clone();
427                                Expression * arg3 = condExpr->get_arg3()->clone();
428                                ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ), mkExpr( arg3 )->acceptMutator( *visitor ) );
429                                ret->set_env( expr->get_env() );
430                                expr->set_env( nullptr );
431                                delete expr;
432
433                                // conditional expr type may not be either of the argument types, need to unify
434                                using namespace ResolvExpr;
435                                Type* commonType = nullptr;
436                                TypeEnvironment newEnv;
437                                AssertionSet needAssertions, haveAssertions;
438                                OpenVarSet openVars;
439                                unify( ret->get_arg2()->get_result(), ret->get_arg3()->get_result(), newEnv, needAssertions, haveAssertions, openVars, SymTab::Indexer(), commonType );
440                                ret->set_result( commonType ? commonType : ret->get_arg2()->get_result()->clone() );
441                                return ret;
442                        }
443                        return expr;
444                }
445
446                Expression * GeneralizedLvalue::postmutate( MemberExpr * memExpr ) {
447                        return applyTransformation( memExpr, memExpr->get_aggregate(), [=]( Expression * aggr ) { return new MemberExpr( memExpr->get_member(), aggr ); } );
448                }
449
450                Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
451                        return applyTransformation( addrExpr, addrExpr->get_arg(), []( Expression * arg ) { return new AddressExpr( arg ); } );
452                }
453
454                Expression * CollapseAddrDeref::postmutate( AddressExpr * addrExpr ) {
455                        Expression * arg = addrExpr->get_arg();
456                        if ( isIntrinsicReference( arg ) ) {
457                                std::string fname = InitTweak::getFunctionName( arg );
458                                if ( fname == "*?" ) {
459                                        Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
460                                        Expression * ret = arg0;
461                                        ret->set_env( addrExpr->get_env() );
462                                        arg0 = nullptr;
463                                        addrExpr->set_env( nullptr );
464                                        delete addrExpr;
465                                        return ret;
466                                }
467                        }
468                        return addrExpr;
469                }
470
471                Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
472                        if ( isIntrinsicReference( appExpr ) ) {
473                                std::string fname = InitTweak::getFunctionName( appExpr );
474                                if ( fname == "*?" ) {
475                                        Expression * arg = InitTweak::getCallArg( appExpr, 0 );
476                                        // xxx - this isn't right, because it can remove casts that should be there...
477                                        // while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
478                                        //      arg = castExpr->get_arg();
479                                        // }
480                                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
481                                                Expression * ret = addrExpr->get_arg();
482                                                ret->set_env( appExpr->get_env() );
483                                                addrExpr->set_arg( nullptr );
484                                                appExpr->set_env( nullptr );
485                                                delete appExpr;
486                                                return ret;
487                                        }
488                                }
489                        }
490                        return appExpr;
491                }
492        } // namespace
493} // namespace GenPoly
494
495// Local Variables: //
496// tab-width: 4 //
497// mode: c++ //
498// compile-command: "make install" //
499// End: //
Note: See TracBrowser for help on using the repository browser.