source: src/GenPoly/Lvalue.cpp @ 525f7ad

Last change on this file since 525f7ad was 85855b0, checked in by JiadaL <j82liang@…>, 4 weeks ago
  1. Implement enum cast; 2. Change valueE so that opague enum returns quasi_void; 3. change enum hiding interpretation and pass visiting scheme
  • Property mode set to 100644
File size: 23.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// Lvalue.cpp -- Clean up lvalues and remove references.
8//
9// Author           : Andrew Beach
10// Created On       : Thu Sep 15 14:08:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Wed Oct  6  9:59:00 2022
13// Update Count     : 0
14//
15
16#include "Lvalue.hpp"
17
18#include <set>
19#include <iostream>
20
21#include "AST/Copy.hpp"                // for deepCopy
22#include "AST/Expr.hpp"
23#include "AST/Inspect.hpp"
24#include "AST/LinkageSpec.hpp"         // for Linkage
25#include "AST/Pass.hpp"
26#include "Common/SemanticError.hpp"    // for SemanticWarning
27#include "Common/ToString.hpp"         // for toCString
28#include "Common/UniqueName.hpp"       // for UniqueName
29#include "GenPoly/GenPoly.hpp"         // for genFunctionType
30#include "ResolvExpr/Typeops.hpp"      // for typesCompatible
31#include "ResolvExpr/Unify.hpp"        // for unify
32
33#if 0
34#define PRINT(x) x
35#else
36#define PRINT(x)
37#endif
38
39namespace GenPoly {
40
41namespace {
42
43/// Intrinsic functions that return references now instead return lvalues.
44struct FixIntrinsicResults final : public ast::WithGuards {
45        enum {
46                NoSkip,
47                Skip,
48                SkipInProgress,
49        } skip = NoSkip;
50
51        void previsit( ast::AsmExpr const * ) {
52                GuardValue( skip ) = Skip;
53        }
54        void previsit( ast::ApplicationExpr const * ) {
55                GuardValue( skip ) = (skip == Skip) ? SkipInProgress : NoSkip;
56        }
57
58        ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
59        void previsit( ast::FunctionDecl const * decl );
60        bool inIntrinsic = false;
61};
62
63/// Add de-references around address-of operations on reference types.
64struct AddressRef final :
65                public ast::WithConstTranslationUnit,
66                public ast::WithGuards,
67                public ast::WithShortCircuiting,
68                public ast::WithVisitorRef<AddressRef> {
69        void previsit( ast::AddressExpr const * expr );
70        ast::Expr const * postvisit( ast::AddressExpr const * expr );
71        void previsit( ast::Expr const * expr );
72        ast::ApplicationExpr const * previsit( ast::ApplicationExpr const * expr );
73        void previsit( ast::SingleInit const * init );
74
75        void handleNonAddr( ast::Expr const * expr );
76
77        bool first = true;
78        bool current = false;
79        bool addCast = false;
80        int refDepth = 0;
81};
82
83/// Handles casts between references and pointers,
84/// creating temporaries for the conversion.
85struct ReferenceConversions final :
86                public ast::WithConstTranslationUnit,
87                public ast::WithGuards, public ast::WithStmtsToAdd<> {
88        ast::Expr const * postvisit( ast::CastExpr const * expr );
89        ast::Expr const * postvisit( ast::AddressExpr const * expr );
90};
91
92/// Intrinsic functions that take reference parameters don't actually do.
93/// Their reference arguments must be implicity dereferenced.
94/// TODO Also appears to contain redundent code with AddressRef
95struct FixIntrinsicArgs final :
96                public ast::WithConstTranslationUnit {
97        ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
98};
99
100/// Removes redundant &* / *& patterns that may be generated.
101struct CollapseAddressDeref final {
102        ast::Expr const * postvisit( ast::AddressExpr const * expr );
103        ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
104};
105
106/// GCC-like Generalized Lvalues (which have since been removed from GCC).
107/// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
108/// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
109struct GeneralizedLvalue final :
110                public ast::WithVisitorRef<GeneralizedLvalue> {
111        ast::Expr const * postvisit( ast::AddressExpr const * expr );
112        ast::Expr const * postvisit( ast::MemberExpr const * expr );
113
114        template<typename Node, typename Func>
115        ast::Expr const * applyTransformation(
116              Node const * expr, ast::ptr<ast::Expr> Node::*field, Func mkExpr );
117};
118
119/// Replace all reference types with pointer types.
120struct ReferenceTypeElimination final {
121        ast::Type const * postvisit( ast::ReferenceType const * type );
122};
123
124/// True for intrinsic function calls that return an lvalue in C.
125bool isIntrinsicReference( ast::Expr const * expr ) {
126        // The known intrinsic-reference prelude functions.
127        static std::set<std::string> const lvalueFunctions = { "*?", "?[?]" };
128        if ( auto untyped = dynamic_cast<ast::UntypedExpr const *>( expr ) ) {
129                std::string fname = ast::getFunctionName( untyped );
130                return lvalueFunctions.count( fname );
131        } else if ( auto app = dynamic_cast<ast::ApplicationExpr const *>( expr ) ) {
132                if ( auto func = ast::getFunction( app ) ) {
133                        return func->linkage == ast::Linkage::Intrinsic
134                                && lvalueFunctions.count( func->name );
135                }
136        }
137        return false;
138}
139
140// A maybe typed variant of the createDeref function (only UntypedExpr).
141ast::Expr * mkDeref(
142                ast::TranslationGlobal const & global, ast::Expr const * arg ) {
143        if ( global.dereference ) {
144                // Note: Reference depth can be arbitrarily deep here,
145                // so peel off the outermost pointer/reference, not just
146                // pointer because they are effecitvely equivalent in this pass
147                ast::VariableExpr * deref = new ast::VariableExpr(
148                        arg->location, global.dereference );
149                deref->result = new ast::PointerType( deref->result );
150                ast::Type const * base = ast::getPointerBase( arg->result );
151                assertf( base, "expected pointer type in dereference (type was %s)", toString( arg->result ).c_str() );
152                ast::ApplicationExpr * ret =
153                        new ast::ApplicationExpr( arg->location, deref, { arg } );
154                ret->result = ast::deepCopy( base );
155                return ret;
156        } else {
157                return ast::UntypedExpr::createDeref( arg->location, arg );
158        }
159}
160
161ast::Expr const * FixIntrinsicResults::postvisit(
162                ast::ApplicationExpr const * expr ) {
163
164        if ( skip == SkipInProgress || !isIntrinsicReference( expr ) ) {
165                return expr;
166        }
167        // Eliminate reference types from intrinsic applications
168        // now they return lvalues.
169        ast::ptr<ast::ReferenceType> result =
170                        expr->result.strict_as<ast::ReferenceType>();
171        expr = ast::mutate_field( expr, &ast::ApplicationExpr::result,
172                        ast::deepCopy( result->base ) );
173        if ( inIntrinsic ) {
174                return expr;
175        }
176        // When not in an intrinsic function, add a cast to don't add cast when
177        // in an intrinsic function, since they already have the cast.
178        auto * ret = new ast::CastExpr( expr->location, expr, result.get() );
179        ret->env = expr->env;
180        return ret;
181}
182
183void FixIntrinsicResults::previsit( ast::FunctionDecl const * decl ) {
184        GuardValue( inIntrinsic ) = decl->linkage == ast::Linkage::Intrinsic;
185}
186
187void AddressRef::previsit( ast::AddressExpr const * ) {
188        // Is this the first address-of in the chain?
189        GuardValue( current ) = first;
190        // Later references will not be for next address-of to be first in chain.
191        GuardValue( first ) = false;
192        // If is the outermost address-of in a chain:
193        if ( current ) {
194                // Set depth to 0 so that postvisit can
195                // find the innermost address-of easily.
196                GuardValue( refDepth ) = 0;
197        }
198}
199
200ast::Expr const * AddressRef::postvisit( ast::AddressExpr const * expr ) {
201        PRINT( std::cerr << "addr ref at " << expr << std::endl; )
202        if ( 0 == refDepth ) {
203                PRINT( std::cerr << "depth 0, get new depth..." << std::endl; )
204                // Is this the innermost address-of in a chain? record depth D.
205                if ( isIntrinsicReference( expr->arg ) ) {
206                        assertf( false, "AddrRef : address-of should not have intrinsic reference argument: %s", toCString( expr->arg )  );
207                } else {
208                        // try to avoid ?[?]
209                        // TODO is this condition still necessary? intrinsicReferences
210                        // should have a cast around them at this point, so I don't think
211                        // this condition ever fires.
212                        refDepth = expr->arg->result->referenceDepth();
213                        PRINT( std::cerr << "arg not intrinsic reference, new depth is: " << refDepth << std::endl; )
214                }
215        }
216        if ( current ) {
217                PRINT( std::cerr << "current, depth is: " << refDepth << std::endl; )
218                ast::Expr const * ret = expr;
219                while ( refDepth ) {
220                        // Add one dereference for each address-of in the chain.
221                        ret = mkDeref( transUnit().global, ret );
222                        --refDepth;
223                }
224
225                // if addrExpr depth is 0, then the result is a pointer because the
226                // arg was depth 1 and not lvalue. This means the dereference result
227                // is not a reference, is lvalue, and one less pointer depth than the
228                // addrExpr. Thus the cast is meaningless.
229                // TODO: One thing to double check is whether it is possible for the
230                // types to differ outside of the single pointer level (i.e. can the
231                // base type of addrExpr differ from the type of addrExpr-arg?). If
232                // so then the cast might need to be added, conditional on a more
233                // sophisticated check.
234                if ( addCast && 0 != expr->result->referenceDepth() ) {
235                        PRINT( std::cerr << "adding cast to " << expr->result << std::endl; )
236                        return new ast::CastExpr( expr->location,
237                                ret, ast::deepCopy( expr->result ) );
238                }
239                return ret;
240        }
241        PRINT( std::cerr << "not current..." << std::endl; )
242        return expr;
243}
244
245void AddressRef::previsit( ast::Expr const * expr ) {
246        handleNonAddr( expr );
247        GuardValue( addCast ) = false;
248}
249
250// So we want to skip traversing to the head?
251ast::ApplicationExpr const * AddressRef::previsit(
252                ast::ApplicationExpr const * expr ) {
253        visit_children = false;
254        GuardValue( addCast );
255        handleNonAddr( expr );
256        auto mutExpr = ast::mutate( expr );
257        for ( ast::ptr<ast::Expr> & arg : mutExpr->args ) {
258                addCast = true;
259                arg = arg->accept( *visitor );
260        }
261        return mutExpr;
262}
263
264void AddressRef::previsit( ast::SingleInit const * ) {
265        // Each initialization context with address-of requires a cast.
266        GuardValue( addCast ) = true;
267}
268
269// idea: &&&E: get outer &, inner &
270// at inner &, record depth D of reference type of argument of &.
271// at auter &, add D derefs.
272void AddressRef::handleNonAddr( ast::Expr const * ) {
273        // non-address-of: reset status variables:
274        // * current expr is NOT the first address-of expr in an address-of chain.
275        // * next seen address-of expr IS the first in the chain.
276        GuardValue( current ) = false;
277        GuardValue( first ) = true;
278}
279
280ast::Expr const * ReferenceConversions::postvisit(
281                ast::CastExpr const * expr ) {
282        // TODO: Is it possible to convert directly between reference types with
283        // a different base. e.g.
284        //   int x;
285        //   (double&)x;
286        // At the moment, I (who?) am working off of the assumption that this is
287        // illegal, thus the cast becomes redundant after this pass, so trash the
288        // cast altogether. If that changes, care must be taken to insert the
289        // correct pointer casts in the right places.
290
291        // Note: reference depth difference is the determining factor in what
292        // code is run, rather than whether something is reference type or not,
293        // since conversion still needs to occur when both types are references
294        // that differ in depth.
295        ast::Type const * dstType = expr->result.get();
296        ast::Type const * srcType = expr->arg->result.get();
297        assertf( dstType, "Cast to no type in: %s", toCString( expr ) );
298        assertf( srcType, "Cast from no type in: %s", toCString( expr ) );
299        int dstDepth = dstType->referenceDepth();
300        int srcDepth = srcType->referenceDepth();
301        int diff = dstDepth - srcDepth;
302
303        if ( 0 < diff && !expr->arg->get_lvalue() ) {
304                // rvalue to reference conversion -- introduce temporary
305                // know that reference depth of cast argument is 0
306                //   (int &&&)3;
307                // becomes
308                //   int __ref_tmp_0 = 3;
309                //   int & __ref_tmp_1 = &__ref_tmp_0;
310                //   int && __ref_tmp_2 = &__ref_tmp_1;
311                //   &__ref_tmp_2;
312                // The last & comes from the remaining reference conversion code.
313                SemanticWarning( expr->arg->location,
314                        Warning::RvalueToReferenceConversion, toCString( expr->arg ) );
315
316                static UniqueName tmpNamer( "__ref_tmp_" );
317                ast::ObjectDecl * tmp = new ast::ObjectDecl( expr->arg->location,
318                        tmpNamer.newName(),
319                        ast::deepCopy( expr->arg->result ),
320                        new ast::SingleInit( expr->arg->location, expr->arg ) );
321                PRINT( std::cerr << "make tmp: " << tmp << std::endl; )
322                stmtsToAddBefore.push_back( new ast::DeclStmt( tmp->location, tmp ) );
323                for ( int i = 0 ; i < dstDepth - 1 ; ++i ) {
324                        ast::ObjectDecl * newTmp = new ast::ObjectDecl( tmp->location,
325                                tmpNamer.newName(),
326                                new ast::ReferenceType( ast::deepCopy( tmp->type ) ),
327                                new ast::SingleInit( tmp->location,
328                                        new ast::AddressExpr( tmp->location,
329                                                new ast::VariableExpr( tmp->location, tmp ) ) ) );
330                        PRINT( std::cerr << "make tmp: " << i << ": " << newTmp << std::endl; )
331                        stmtsToAddBefore.push_back(
332                                new ast::DeclStmt( newTmp->location, newTmp ) );
333                        tmp = newTmp;
334                }
335                // Update diff so that remaining code works out correctly.
336                expr = ast::mutate_field( expr, &ast::CastExpr::arg,
337                        new ast::VariableExpr( tmp->location, tmp ) );
338                PRINT( std::cerr << "update cast to: " << expr << std::endl; )
339                srcType = expr->arg->result;
340                srcDepth = srcType->referenceDepth();
341                diff = dstDepth - srcDepth;
342                assert( 1 == diff );
343        }
344
345        // Handle conversion between different depths.
346        PRINT(
347                if ( dstDepth || srcDepth ) {
348                        std::cerr << "dstType: " << dstType << " / srcType: " << srcType << '\n';
349                        std::cerr << "depth: " << dstDepth << " / " << srcDepth << std::endl;
350                }
351        )
352        // Conversion to type with more depth/more references.
353        // Add address-of for each level of difference.
354        if ( 0 < diff ) {
355                ast::Expr * ret = ast::mutate( expr->arg.get() );
356                for ( int i = 0 ; i < diff ; ++i ) {
357                        ret = new ast::AddressExpr( ret->location, ret );
358                }
359                if ( expr->arg->get_lvalue() &&
360                                !ResolvExpr::typesCompatible(
361                                        srcType,
362                                        strict_dynamic_cast<ast::ReferenceType const *>( dstType )->base ) ) {
363                        // Must keep cast if cast-to type is different from the actual type.
364                        return ast::mutate_field( expr, &ast::CastExpr::arg, ret );
365                }
366                ret->env = expr->env;
367                ret->result = expr->result;
368                return ret;
369        // Conversion to type with less depth/fewer references.
370        // Add dereferences for each level of difference.
371        } else if ( diff < 0 ) {
372                ast::Expr * ret = ast::mutate( expr->arg.get() );
373                for ( int i = 0 ; i < -diff ; ++i ) {
374                        ret = mkDeref( transUnit().global, ret );
375                }
376                // Must keep cast if types are different.
377                if ( !ResolvExpr::typesCompatibleIgnoreQualifiers(
378                                dstType->stripReferences(),
379                                srcType->stripReferences() ) ) {
380                        return ast::mutate_field( expr, &ast::CastExpr::arg, ret );
381                }
382                ret->env = expr->env;
383                ret->result = expr->result;
384                // The result must be an lvalue.
385                assert( ret->get_lvalue() );
386                return ret;
387        // Conversion with the same depth.
388        } else {
389                assert( 0 == diff );
390                // Remove useless generated casts.
391                if ( expr->isGenerated == ast::GeneratedFlag::GeneratedCast &&
392                                ResolvExpr::typesCompatible(
393                                        expr->result,
394                                        expr->arg->result ) ) {
395                        PRINT(
396                                std::cerr << "types are compatible, removing cast: " << expr << '\n';
397                                std::cerr << "-- " << expr->result << '\n';
398                                std::cerr << "-- " << expr->arg->result << std::endl;
399                        )
400                        auto argAsEnum = expr->arg.as<ast::EnumInstType>();
401                        auto resultAsEnum = expr->result.as<ast::EnumInstType>();
402                        if (argAsEnum && resultAsEnum) {
403                                if (argAsEnum->base->name != resultAsEnum->base->name) {
404                                        return expr;
405                                }
406                        }
407                        return ast::mutate_field( expr->arg.get(),
408                                        &ast::Expr::env, expr->env.get() );
409                }
410                return expr;
411        }
412}
413
414ast::Expr const * ReferenceConversions::postvisit(
415                ast::AddressExpr const * expr ) {
416        // Inner expression may have been lvalue to reference conversion, which
417        // becomes an address expression. In this case, remove the outer address
418        // expression and return the argument.
419        // TODO: It's possible that this might catch too much and require a more
420        // sophisticated check. TODO What check are we talking about here?
421        return expr;
422}
423
424ast::Expr const * FixIntrinsicArgs::postvisit(
425                ast::ApplicationExpr const * expr ) {
426        // Intrinsic functions don't really take reference-typed parameters,
427        // so they require an implicit dereference on their arguments.
428        auto function = ast::getFunction( expr );
429        if ( function == nullptr ) {
430                return expr;
431        }
432
433        ast::FunctionType const * ftype = GenPoly::getFunctionType( function->get_type() );
434        assertf( ftype, "Function declaration does not have function type." );
435        // Can be of different lengths only when function is variadic.
436        assertf( ftype->params.size() == expr->args.size() || ftype->isVarArgs,
437                "ApplicationExpr args do not match formal parameter type." );
438        assertf( ftype->params.size() <= expr->args.size(),
439                "Cannot have more parameters than arguments." );
440
441        unsigned int i = 0;
442        unsigned int const end = ftype->params.size();
443
444        // This is used to make sure we get a zip on shortests.
445        if ( end == i ) return expr;
446
447        // This mutate could be redundent, but it is simpler this way.
448        auto mutExpr = ast::mutate( expr );
449
450        for ( auto pair : unsafe_group_iterate( mutExpr->args, ftype->params ) ) {
451                ast::ptr<ast::Expr> & arg = std::get<0>( pair );
452                ast::ptr<ast::Type> const & formal = std::get<1>( pair );
453                PRINT(
454                        std::cerr << "pair<0>: " << arg.get() << std::endl;
455                        std::cerr << " -- " << arg->result << std::endl;
456                        std::cerr << "pair<1>: " << formal << std::endl;
457                )
458                //if ( dynamic_cast<ast::ReferenceType const *>( formal.get() ) ) {
459                if ( formal.as<ast::ReferenceType>() ) {
460                        PRINT( std::cerr << "===formal is reference" << std::endl; )
461                        // TODO: It's likely that the second condition should be
462                        // `... && ! isIntrinsicReference( arg )`, but this requires
463                        // investigation.
464
465                        if ( ast::Linkage::Intrinsic != function->linkage
466                                        && isIntrinsicReference( arg ) ) {
467                                // Needed for definition of prelude functions, etc.
468                                // If argument is dereference or array subscript, the result
469                                // isn't REALLY a reference, but non-intrinsic functions
470                                // expect a reference: take address
471
472                                // TODO: OK, so this should be cut?!
473                                // NODE: Previously, this condition fixed
474                                //   void f(int *&);
475                                //   int & x = ...;
476                                //   f(&x);
477                                // But now this is taken care of by a reference cast added by
478                                // AddressRef. Need to find a new example or remove this
479                                // branch.
480                                PRINT(
481                                        std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
482                                )
483                                arg = new ast::AddressExpr( arg->location, arg );
484                        } else if ( ast::Linkage::Intrinsic == function->linkage
485                                        && arg->result->referenceDepth() != 0 ) {
486                                // Argument is a 'real' reference, but function expects a C
487                                // lvalue: Add a dereference to the reference-typed argument.
488                                PRINT(
489                                        std::cerr << "===is non-intrinsic arg in intrinsic call - adding deref to arg" << std::endl;
490                                )
491                                ast::Type const * base = ast::getPointerBase( arg->result );
492                                assertf( base, "parameter is reference, arg must be pointer or reference: %s", toString( arg->result ).c_str() );
493                                ast::PointerType * ptr = new ast::PointerType( ast::deepCopy( base ) );
494                                arg = ast::mutate_field( arg.get(),
495                                                &ast::ApplicationExpr::result, ptr );
496                                arg = mkDeref( transUnit().global, arg );
497                        }
498                }
499                ++i;
500                if ( end == i ) break;
501        }
502        return mutExpr;
503}
504
505ast::Expr const * CollapseAddressDeref::postvisit(
506                ast::AddressExpr const * expr ) {
507        ast::Expr const * arg = expr->arg;
508        if ( isIntrinsicReference( arg ) ) {
509                std::string fname = ast::getFunctionName( arg );
510                if ( fname == "*?" ) {
511                        ast::Expr const * arg0 = ast::getCallArg( arg, 0 );
512                        ast::Expr * ret = ast::mutate( arg0 );
513                        ret->env = expr->env;
514                        return ret;
515                }
516        } else if ( auto cast = dynamic_cast<ast::CastExpr const *>( arg ) ) {
517                // Need to move cast to pointer type out a level since address of
518                // pointer is not valid C code (can be introduced in prior passes,
519                // e.g., InstantiateGeneric)
520                if ( ast::getPointerBase( cast->result ) ) {
521                        auto mutExpr = ast::mutate( expr );
522                        auto mutCast = strict_dynamic_cast<ast::CastExpr *>(
523                                        ast::mutate( mutExpr->arg.release() ) );
524                        mutExpr->arg = mutCast->arg;
525                        mutCast->arg = mutExpr;
526                        mutCast->result = new ast::PointerType( mutCast->result );
527                        return mutCast;
528                }
529        }
530        return expr;
531}
532
533ast::Expr const * CollapseAddressDeref::postvisit(
534                ast::ApplicationExpr const * expr ) {
535        if ( isIntrinsicReference( expr ) ) {
536                std::string fname = ast::getFunctionName( expr );
537                if ( fname == "*?" ) {
538                        assert( 1 == expr->args.size() );
539                        ast::Expr const * arg = ast::getCallArg( expr, 0 );
540                        // xxx - this isn't right, because it can remove casts that
541                        // should be there...
542                        //      while ( auto cast = dynamic_cast< ast::CastExpr const * >( arg ) ) {
543                        //              arg = cast->arg;
544                        //      }
545                        if ( auto addr = dynamic_cast<ast::AddressExpr const *>( arg ) ) {
546                                return ast::mutate_field( addr->arg.get(),
547                                                &ast::Expr::env, expr->env.get() );
548                        }
549                }
550        }
551        return expr;
552}
553
554ast::Expr const * GeneralizedLvalue::postvisit(
555                ast::AddressExpr const * expr ) {
556        return applyTransformation( expr, &ast::AddressExpr::arg,
557                []( ast::Expr const * arg ) {
558                        return new ast::AddressExpr( arg->location, arg );
559                }
560        );
561}
562
563ast::Expr const * GeneralizedLvalue::postvisit(
564                ast::MemberExpr const * expr ) {
565        return applyTransformation( expr, &ast::MemberExpr::aggregate,
566                [expr]( ast::Expr const * aggr ) {
567                        return new ast::MemberExpr( aggr->location, expr->member, aggr );
568                }
569        );
570}
571
572template<typename Node, typename Func>
573ast::Expr const * GeneralizedLvalue::applyTransformation(
574                Node const * expr, ast::ptr<ast::Expr> Node::*field, Func mkExpr ) {
575        ast::ptr<ast::Expr> const & arg = expr->*field;
576        if ( auto commaArg = arg.as<ast::CommaExpr>() ) {
577                ast::Expr const * arg1 = ast::deepCopy( commaArg->arg1 );
578                ast::Expr const * arg2 = ast::deepCopy( commaArg->arg2 );
579                ast::Expr const * ret = new ast::CommaExpr(
580                        commaArg->location, arg1, mkExpr( arg2 )->accept( *visitor ) );
581                return ret;
582        } else if ( auto condArg = arg.as<ast::ConditionalExpr>() ) {
583                ast::Expr const * arg1 = ast::deepCopy( condArg->arg1 );
584                ast::Expr const * arg2 = ast::deepCopy( condArg->arg2 );
585                ast::Expr const * arg3 = ast::deepCopy( condArg->arg3 );
586                ast::ConditionalExpr * ret = new ast::ConditionalExpr(
587                        condArg->location, arg1, mkExpr( arg2 )->accept( *visitor ),
588                        mkExpr( arg3 )->accept( *visitor ) );
589
590                // Conditional expr type may not be either of the arguments,
591                // so unify to get the result.
592                // TODO: Maybe I could create a wrapper for this.
593                ast::ptr<ast::Type> common = nullptr;
594                ast::TypeEnvironment newEnv;
595                ast::AssertionSet needAssertions, haveAssertions;
596                ast::OpenVarSet openVars;
597                ResolvExpr::unify( ret->arg2->result, ret->arg3->result, newEnv,
598                        needAssertions, haveAssertions, openVars, common );
599                ret->result = common ? common : ast::deepCopy( ret->arg2->result );
600                return ret;
601        }
602        return expr;
603}
604
605ast::Type const * ReferenceTypeElimination::postvisit(
606                ast::ReferenceType const * type ) {
607        return new ast::PointerType( type->base, type->qualifiers );
608}
609
610} // namespace
611
612// Stored elsewhere (Lvalue2, initially false):
613extern bool referencesEliminated;
614
615void convertLvalue( ast::TranslationUnit & translationUnit ) {
616        ast::Pass<FixIntrinsicResults>::run( translationUnit );
617        ast::Pass<AddressRef>::run( translationUnit );
618        ast::Pass<ReferenceConversions>::run( translationUnit );
619        ast::Pass<FixIntrinsicArgs>::run( translationUnit );
620        ast::Pass<CollapseAddressDeref>::run( translationUnit );
621        ast::Pass<GeneralizedLvalue>::run( translationUnit );
622        // Last because other passes need reference types to work.
623        ast::Pass<ReferenceTypeElimination>::run( translationUnit );
624        // From this point forward, nothing should create reference types.
625        referencesEliminated = true;
626}
627
628ast::Expr const * generalizedLvalue( ast::Expr const * expr ) {
629        ast::Pass<GeneralizedLvalue> visitor;
630        return expr->accept( visitor );
631}
632
633} // namespace GenPoly
634
635// Local Variables: //
636// tab-width: 4 //
637// mode: c++ //
638// compile-command: "make install" //
639// End: //
Note: See TracBrowser for help on using the repository browser.