source: src/GenPoly/Lvalue.cc @ 2c04369

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2c04369 was 2c04369, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Fixed some problems in convert. One of which was better solved by removing the FindSpecialDeclarations? hack.

  • Property mode set to 100644
File size: 23.7 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 : Andrew Beach
12// Last Modified On : Tue May 28 11:07:00 2019
13// Update Count     : 6
14//
15
16#include <cassert>                       // for strict_dynamic_cast
17#include <string>                        // for string
18
19#include "Common/PassVisitor.h"
20#include "GenPoly.h"                     // for isPolyType
21#include "Lvalue.h"
22
23#include "Parser/LinkageSpec.h"          // for Spec, isBuiltin, Intrinsic
24#include "ResolvExpr/TypeEnvironment.h"  // for AssertionSet, OpenVarSet
25#include "ResolvExpr/Unify.h"            // for unify
26#include "ResolvExpr/typeops.h"
27#include "SymTab/Autogen.h"
28#include "SymTab/Indexer.h"              // for Indexer
29#include "SynTree/Declaration.h"         // for Declaration, FunctionDecl
30#include "SynTree/Expression.h"          // for Expression, ConditionalExpr
31#include "SynTree/Mutator.h"             // for mutateAll, Mutator
32#include "SynTree/Statement.h"           // for ReturnStmt, Statement (ptr o...
33#include "SynTree/Type.h"                // for PointerType, Type, FunctionType
34#include "SynTree/Visitor.h"             // for Visitor, acceptAll
35
36#if 0
37#define PRINT(x) x
38#else
39#define PRINT(x)
40#endif
41
42namespace GenPoly {
43        namespace {
44                /// Local helper for pass visitors that need to add reference operations.
45                struct WithDerefOp {
46                        FunctionDecl * dereferenceOperator = nullptr;
47
48                        // TODO: fold this into the general createDeref function??
49                        Expression * mkDeref( Expression * arg ) {
50                                if ( dereferenceOperator ) {
51                                        // note: reference depth can be arbitrarily deep here, so peel off the
52                                        // outermost pointer/reference, not just pointer because they are effecitvely
53                                        // equivalent in this pass
54                                        VariableExpr * deref = new VariableExpr( dereferenceOperator );
55                                        deref->result = new PointerType( Type::Qualifiers(), deref->result );
56                                        Type * base = InitTweak::getPointerBase( arg->result );
57                                        assertf( base, "expected pointer type in dereference (type was %s)",
58                                                toString( arg->result ).c_str() );
59                                        ApplicationExpr * ret = new ApplicationExpr( deref, { arg } );
60                                        delete ret->result;
61                                        ret->result = base->clone();
62                                        ret->result->set_lvalue( true );
63                                        return ret;
64                                } else {
65                                        return UntypedExpr::createDeref( arg );
66                                }
67                        }
68
69                        void previsit( FunctionDecl * funcDecl ) {
70                                if ( dereferenceOperator ) return;
71                                if ( funcDecl->get_name() != "*?" ) return;
72                                if ( funcDecl->get_linkage() == LinkageSpec::Intrinsic ) return;
73                                FunctionType * ftype = funcDecl->get_functionType();
74                                if ( ftype->get_parameters().size() != 1 ) return;
75                                DeclarationWithType * arg0 = ftype->get_parameters().front();
76                                if ( arg0->get_type()->get_qualifiers() == Type::Qualifiers() ) return;
77                                dereferenceOperator = funcDecl;
78                        }
79                };
80
81                struct ReferenceConversions final : public WithStmtsToAdd, public WithDerefOp {
82                        Expression * postmutate( CastExpr * castExpr );
83                        Expression * postmutate( AddressExpr * addrExpr );
84                };
85
86                /// Intrinsic functions that take reference parameters don't REALLY take reference parameters -- their reference arguments must always be implicitly dereferenced.
87                struct FixIntrinsicArgs final : public WithDerefOp {
88                        Expression * postmutate( ApplicationExpr * appExpr );
89                };
90
91                struct FixIntrinsicResult final : public WithGuards {
92                        Expression * postmutate( ApplicationExpr * appExpr );
93                        void premutate( FunctionDecl * funcDecl );
94                        bool inIntrinsic = false;
95                };
96
97                /// Replace reference types with pointer types
98                struct ReferenceTypeElimination final {
99                        Type * postmutate( ReferenceType * refType );
100                };
101
102                /// GCC-like Generalized Lvalues (which have since been removed from GCC)
103                /// https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Lvalues.html#Lvalues
104                /// Replaces &(a,b) with (a, &b), &(a ? b : c) with (a ? &b : &c)
105                struct GeneralizedLvalue final : public WithVisitorRef<GeneralizedLvalue> {
106                        Expression * postmutate( AddressExpr * addressExpr );
107                        Expression * postmutate( MemberExpr * memExpr );
108
109                        template<typename Func>
110                        Expression * applyTransformation( Expression * expr, Expression * arg, Func mkExpr );
111                };
112
113                /// Removes redundant &*/*& pattern that this pass can generate
114                struct CollapseAddrDeref final {
115                        Expression * postmutate( AddressExpr * addressExpr );
116                        Expression * postmutate( ApplicationExpr * appExpr );
117                };
118
119                struct AddrRef final : public WithGuards, public WithVisitorRef<AddrRef>,
120                                public WithShortCircuiting, public WithDerefOp {
121                        void premutate( AddressExpr * addrExpr );
122                        Expression * postmutate( AddressExpr * addrExpr );
123                        void premutate( Expression * expr );
124                        void premutate( ApplicationExpr * appExpr );
125                        void premutate( SingleInit * init );
126
127                        void handleNonAddr( Expression * );
128
129                        bool first = true;
130                        bool current = false;
131                        int refDepth = 0;
132                        bool addCast = false;
133                };
134        } // namespace
135
136        static bool referencesEliminated = false;
137        // used by UntypedExpr::createDeref to determine whether result type of dereference should be ReferenceType or value type.
138        bool referencesPermissable() {
139                return ! referencesEliminated;
140        }
141
142        void convertLvalue( std::list< Declaration* > & translationUnit ) {
143                PassVisitor<ReferenceConversions> refCvt;
144                PassVisitor<ReferenceTypeElimination> elim;
145                PassVisitor<GeneralizedLvalue> genLval;
146                PassVisitor<FixIntrinsicArgs> fixer;
147                PassVisitor<CollapseAddrDeref> collapser;
148                PassVisitor<AddrRef> addrRef;
149                PassVisitor<FixIntrinsicResult> intrinsicResults;
150                mutateAll( translationUnit, intrinsicResults );
151                mutateAll( translationUnit, addrRef );
152                mutateAll( translationUnit, refCvt );
153                mutateAll( translationUnit, fixer );
154                mutateAll( translationUnit, collapser );
155                mutateAll( translationUnit, genLval );
156                mutateAll( translationUnit, elim );  // last because other passes need reference types to work
157
158                // from this point forward, no other pass should create reference types.
159                referencesEliminated = true;
160        }
161
162        Expression * generalizedLvalue( Expression * expr ) {
163                PassVisitor<GeneralizedLvalue> genLval;
164                return expr->acceptMutator( genLval );
165        }
166
167        namespace {
168                // true for intrinsic function calls that return an lvalue in C
169                bool isIntrinsicReference( Expression * expr ) {
170                        // known intrinsic-reference prelude functions
171                        static std::set<std::string> lvalueFunctions = { "*?", "?[?]" };
172                        if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * >( expr ) ) {
173                                std::string fname = InitTweak::getFunctionName( untyped );
174                                return lvalueFunctions.count(fname);
175                        } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
176                                if ( DeclarationWithType * func = InitTweak::getFunction( appExpr ) ) {
177                                        return func->linkage == LinkageSpec::Intrinsic && lvalueFunctions.count(func->name);
178                                }
179                        }
180                        return false;
181                }
182
183                Expression * FixIntrinsicResult::postmutate( ApplicationExpr * appExpr ) {
184                        if ( isIntrinsicReference( appExpr ) ) {
185                                // eliminate reference types from intrinsic applications - now they return lvalues
186                                ReferenceType * result = strict_dynamic_cast< ReferenceType * >( appExpr->result );
187                                appExpr->result = result->base->clone();
188                                appExpr->result->set_lvalue( true );
189                                if ( ! inIntrinsic ) {
190                                        // when not in an intrinsic function, add a cast to
191                                        // don't add cast when in an intrinsic function, since they already have the cast
192                                        Expression * ret = new CastExpr( appExpr, result );
193                                        std::swap( ret->env, appExpr->env );
194                                        return ret;
195                                }
196                                delete result;
197                        }
198                        return appExpr;
199                }
200
201                void FixIntrinsicResult::premutate( FunctionDecl * funcDecl ) {
202                        GuardValue( inIntrinsic );
203                        inIntrinsic = funcDecl->linkage == LinkageSpec::Intrinsic;
204                }
205
206                Expression * FixIntrinsicArgs::postmutate( ApplicationExpr * appExpr ) {
207                        // intrinsic functions don't really take reference-typed parameters, so they require an implicit dereference on their arguments.
208                        if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
209                                FunctionType * ftype = GenPoly::getFunctionType( function->get_type() );
210                                assertf( ftype, "Function declaration does not have function type." );
211                                // can be of differing lengths only when function is variadic
212                                assertf( ftype->parameters.size() == appExpr->args.size() || ftype->isVarArgs, "ApplicationExpr args do not match formal parameter type." );
213
214
215                                unsigned int i = 0;
216                                const unsigned int end = ftype->parameters.size();
217                                for ( auto p : unsafe_group_iterate( appExpr->args, ftype->parameters ) ) {
218                                        if (i == end) break;
219                                        Expression *& arg = std::get<0>( p );
220                                        Type * formal = std::get<1>( p )->get_type();
221                                        PRINT(
222                                                std::cerr << "pair<0>: " << arg << std::endl;
223                                                std::cerr << " -- " << arg->result << std::endl;
224                                                std::cerr << "pair<1>: " << formal << std::endl;
225                                        )
226                                        if ( dynamic_cast<ReferenceType*>( formal ) ) {
227                                                PRINT(
228                                                        std::cerr << "===formal is reference" << std::endl;
229                                                )
230                                                // TODO: it's likely that the second condition should be ... && ! isIntrinsicReference( arg ), but this requires investigation.
231
232                                                if ( function->linkage != LinkageSpec::Intrinsic && isIntrinsicReference( arg ) ) {
233                                                        // needed for definition of prelude functions, etc.
234                                                        // if argument is dereference or array subscript, the result isn't REALLY a reference, but non-intrinsic functions expect a reference: take address
235
236                                                        // NOTE: previously, this condition fixed
237                                                        //   void f(int *&);
238                                                        //   int & x = ...;
239                                                        //   f(&x);
240                                                        // But now this is taken care of by a reference cast added by AddrRef. Need to find a new
241                                                        // example or remove this branch.
242
243                                                        PRINT(
244                                                                std::cerr << "===is intrinsic arg in non-intrinsic call - adding address" << std::endl;
245                                                        )
246                                                        arg = new AddressExpr( arg );
247                                                // } else if ( function->get_linkage() == LinkageSpec::Intrinsic && InitTweak::getPointerBase( arg->result ) ) {
248                                                } else if ( function->linkage == LinkageSpec::Intrinsic && arg->result->referenceDepth() != 0 ) {
249                                                        // argument is a 'real' reference, but function expects a C lvalue: add a dereference to the reference-typed argument
250                                                        PRINT(
251                                                                std::cerr << "===is non-intrinsic arg in intrinsic call - adding deref to arg" << std::endl;
252                                                        )
253                                                        Type * baseType = InitTweak::getPointerBase( arg->result );
254                                                        assertf( baseType, "parameter is reference, arg must be pointer or reference: %s", toString( arg->result ).c_str() );
255                                                        PointerType * ptrType = new PointerType( Type::Qualifiers(), baseType->clone() );
256                                                        delete arg->result;
257                                                        arg->result = ptrType;
258                                                        arg = mkDeref( arg );
259                                                        // assertf( arg->result->referenceDepth() == 0, "Reference types should have been eliminated from intrinsic function calls, but weren't: %s", toCString( arg->result ) );
260                                                }
261                                        }
262                                        ++i;
263                                }
264                        }
265                        return appExpr;
266                }
267
268                // idea: &&&E: get outer &, inner &
269                // at inner &, record depth D of reference type of argument of &
270                // at outer &, add D derefs.
271                void AddrRef::handleNonAddr( Expression * ) {
272                        // non-address-of: reset status variables:
273                        // * current expr is NOT the first address-of expr in an address-of chain
274                        // * next seen address-of expr IS the first in the chain.
275                        GuardValue( current );
276                        GuardValue( first );
277                        current = false;
278                        first = true;
279                }
280
281                void AddrRef::premutate( Expression * expr ) {
282                        handleNonAddr( expr );
283                        GuardValue( addCast );
284                        addCast = false;
285                }
286
287                void AddrRef::premutate( AddressExpr * ) {
288                        GuardValue( current );
289                        GuardValue( first );
290                        current = first; // is this the first address-of in the chain?
291                        first = false;   // from here out, no longer possible for next address-of to be first in chain
292                        if ( current ) { // this is the outermost address-of in a chain
293                                GuardValue( refDepth );
294                                refDepth = 0;  // set depth to 0 so that postmutate can find the innermost address-of easily
295                        }
296                }
297
298                Expression * AddrRef::postmutate( AddressExpr * addrExpr ) {
299                        PRINT( std::cerr << "addr ref at " << addrExpr << std::endl; )
300                        if ( refDepth == 0 ) {
301                                PRINT( std::cerr << "depth 0, get new depth..." << std::endl; )
302                                // this is the innermost address-of in a chain, record depth D
303                                if ( ! isIntrinsicReference( addrExpr->arg ) ) {
304                                        // try to avoid ?[?]
305                                        // xxx - is this condition still necessary? intrinsicReferences should have a cast around them at this point, so I don't think this condition ever fires.
306                                        refDepth = addrExpr->arg->result->referenceDepth();
307                                        PRINT( std::cerr << "arg not intrinsic reference, new depth is: " << refDepth << std::endl; )
308                                } else {
309                                        assertf( false, "AddrRef : address-of should not have intrinsic reference argument: %s", toCString( addrExpr->arg ) );
310                                }
311                        }
312                        if ( current ) { // this is the outermost address-of in a chain
313                                PRINT( std::cerr << "current, depth is: " << refDepth << std::endl; )
314                                Expression * ret = addrExpr;
315                                while ( refDepth ) {
316                                        // add one dereference for each
317                                        ret = mkDeref( ret );
318                                        refDepth--;
319                                }
320
321                                // if addrExpr depth is 0, then the result is a pointer because the arg was depth 1 and not lvalue.
322                                // This means the dereference result is not a reference, is lvalue, and one less pointer depth than
323                                // the addrExpr. Thus the cast is meaningless.
324                                // TODO: One thing to double check is whether it is possible for the types to differ outside of the single
325                                // pointer level (i.e. can the base type of addrExpr differ from the type of addrExpr-arg?).
326                                // If so then the cast might need to be added, conditional on a more sophisticated check.
327                                if ( addCast && addrExpr->result->referenceDepth() != 0 ) {
328                                        PRINT( std::cerr << "adding cast to " << addrExpr->result << std::endl; )
329                                        return new CastExpr( ret, addrExpr->result->clone() );
330                                }
331                                return ret;
332                        }
333                        PRINT( std::cerr << "not current..." << std::endl; )
334                        return addrExpr;
335                }
336
337                void AddrRef::premutate( ApplicationExpr * appExpr ) {
338                        visit_children = false;
339                        GuardValue( addCast );
340                        handleNonAddr( appExpr );
341                        for ( Expression *& arg : appExpr->args ) {
342                                // each argument with address-of requires a cast
343                                addCast = true;
344                                arg = arg->acceptMutator( *visitor );
345                        }
346                }
347
348                void AddrRef::premutate( SingleInit * ) {
349                        GuardValue( addCast );
350                        // each initialization context with address-of requires a cast
351                        addCast = true;
352                }
353
354
355                Expression * ReferenceConversions::postmutate( AddressExpr * addrExpr ) {
356                        // Inner expression may have been lvalue to reference conversion, which becomes an address expression.
357                        // In this case, remove the outer address expression and return the argument.
358                        // TODO: It's possible that this might catch too much and require a more sophisticated check.
359                        return addrExpr;
360                }
361
362                Expression * ReferenceConversions::postmutate( CastExpr * castExpr ) {
363                        // xxx - is it possible to convert directly between reference types with a different base? E.g.,
364                        //   int x;
365                        //   (double&)x;
366                        // At the moment, I am working off of the assumption that this is illegal, thus the cast becomes redundant
367                        // after this pass, so trash the cast altogether. If that changes, care must be taken to insert the correct
368                        // pointer casts in the right places.
369
370                        // Note: reference depth difference is the determining factor in what code is run, rather than whether something is
371                        // reference type or not, since conversion still needs to occur when both types are references that differ in depth.
372
373                        Type * destType = castExpr->result;
374                        Type * srcType = castExpr->arg->result;
375                        int depth1 = destType->referenceDepth();
376                        int depth2 = srcType->referenceDepth();
377                        int diff = depth1 - depth2;
378
379                        if ( diff > 0 && ! srcType->get_lvalue() ) {
380                                // rvalue to reference conversion -- introduce temporary
381                                // know that reference depth of cast argument is 0, need to introduce n temporaries for reference depth of n, e.g.
382                                //   (int &&&)3;
383                                // becomes
384                                //   int __ref_tmp_0 = 3;
385                                //   int & __ref_tmp_1 = _&_ref_tmp_0;
386                                //   int && __ref_tmp_2 = &__ref_tmp_1;
387                                //   &__ref_tmp_2;
388                                // the last & comes from the remaining reference conversion code
389                                SemanticWarning( castExpr->arg->location, Warning::RvalueToReferenceConversion, toCString( castExpr->arg ) );
390
391                                static UniqueName tempNamer( "__ref_tmp_" );
392                                ObjectDecl * temp = ObjectDecl::newObject( tempNamer.newName(), castExpr->arg->result->clone(), new SingleInit( castExpr->arg ) );
393                                PRINT( std::cerr << "made temp: " << temp << std::endl; )
394                                stmtsToAddBefore.push_back( new DeclStmt( temp ) );
395                                for ( int i = 0; i < depth1-1; i++ ) { // xxx - maybe this should be diff-1? check how this works with reference type for srcType
396                                        ObjectDecl * newTemp = ObjectDecl::newObject( tempNamer.newName(), new ReferenceType( Type::Qualifiers(), temp->type->clone() ), new SingleInit( new AddressExpr( new VariableExpr( temp ) ) ) );
397                                        PRINT( std::cerr << "made temp" << i << ": " << newTemp << std::endl; )
398                                        stmtsToAddBefore.push_back( new DeclStmt( newTemp ) );
399                                        temp = newTemp;
400                                }
401                                // update diff so that remaining code works out correctly
402                                castExpr->arg = new VariableExpr( temp );
403                                PRINT( std::cerr << "update cast to: " << castExpr << std::endl; )
404                                srcType = castExpr->arg->result;
405                                depth2 = srcType->referenceDepth();
406                                diff = depth1 - depth2;
407                                assert( diff == 1 );
408                        }
409
410                        // handle conversion between different depths
411                        PRINT (
412                                if ( depth1 || depth2 ) {
413                                        std::cerr << "destType: " << destType << " / srcType: " << srcType << std::endl;
414                                        std::cerr << "depth: " << depth1 << " / " << depth2 << std::endl;
415                                }
416                        )
417                        if ( diff > 0 ) {
418                                // conversion to type with more depth (e.g. int & -> int &&): add address-of for each level of difference
419                                Expression * ret = castExpr->arg;
420                                for ( int i = 0; i < diff; ++i ) {
421                                        ret = new AddressExpr( ret );
422                                }
423                                if ( srcType->get_lvalue() && ! ResolvExpr::typesCompatible( srcType, strict_dynamic_cast<ReferenceType *>( destType )->base, SymTab::Indexer() ) ) {
424                                        // must keep cast if cast-to type is different from the actual type
425                                        castExpr->arg = ret;
426                                        return castExpr;
427                                }
428                                ret->env = castExpr->env;
429                                delete ret->result;
430                                ret->result = castExpr->result;
431                                castExpr->env = nullptr;
432                                castExpr->arg = nullptr;
433                                castExpr->result = nullptr;
434                                delete castExpr;
435                                return ret;
436                        } else if ( diff < 0 ) {
437                                // conversion to type with less depth (e.g. int && -> int &): add dereferences for each level of difference
438                                diff = -diff; // care only about magnitude now
439                                Expression * ret = castExpr->arg;
440                                for ( int i = 0; i < diff; ++i ) {
441                                        ret = mkDeref( ret );
442                                        // xxx - try removing one reference here? actually, looks like mkDeref already does this, so more closely look at the types generated.
443                                }
444                                if ( ! ResolvExpr::typesCompatibleIgnoreQualifiers( destType->stripReferences(), srcType->stripReferences(), SymTab::Indexer() ) ) {
445                                        // must keep cast if types are different
446                                        castExpr->arg = ret;
447                                        return castExpr;
448                                }
449                                ret->env = castExpr->env;
450                                delete ret->result;
451                                ret->result = castExpr->result;
452                                ret->result->set_lvalue( true ); // ensure result is lvalue
453                                castExpr->env = nullptr;
454                                castExpr->arg = nullptr;
455                                castExpr->result = nullptr;
456                                delete castExpr;
457                                return ret;
458                        } else {
459                                assert( diff == 0 );
460                                // conversion between references of the same depth
461                                if ( ResolvExpr::typesCompatible( castExpr->result, castExpr->arg->result, SymTab::Indexer() ) && castExpr->isGenerated ) {
462                                        // Remove useless generated casts
463                                        PRINT(
464                                                std::cerr << "types are compatible, removing cast: " << castExpr << std::endl;
465                                                std::cerr << "-- " << castExpr->result << std::endl;
466                                                std::cerr << "-- " << castExpr->arg->result << std::endl;
467                                        )
468                                        Expression * ret = castExpr->arg;
469                                        castExpr->arg = nullptr;
470                                        std::swap( castExpr->env, ret->env );
471                                        delete castExpr;
472                                        return ret;
473                                }
474                                return castExpr;
475                        }
476                }
477
478                Type * ReferenceTypeElimination::postmutate( ReferenceType * refType ) {
479                        Type * base = refType->base;
480                        Type::Qualifiers qualifiers = refType->get_qualifiers();
481                        refType->base = nullptr;
482                        delete refType;
483                        return new PointerType( qualifiers, base );
484                }
485
486                template<typename Func>
487                Expression * GeneralizedLvalue::applyTransformation( Expression * expr, Expression * arg, Func mkExpr ) {
488                        if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( arg ) ) {
489                                Expression * arg1 = commaExpr->arg1->clone();
490                                Expression * arg2 = commaExpr->arg2->clone();
491                                Expression * ret = new CommaExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ) );
492                                ret->env = expr->env;
493                                expr->env = nullptr;
494                                delete expr;
495                                return ret;
496                        } else if ( ConditionalExpr * condExpr = dynamic_cast< ConditionalExpr * >( arg ) ) {
497                                Expression * arg1 = condExpr->arg1->clone();
498                                Expression * arg2 = condExpr->arg2->clone();
499                                Expression * arg3 = condExpr->arg3->clone();
500                                ConditionalExpr * ret = new ConditionalExpr( arg1, mkExpr( arg2 )->acceptMutator( *visitor ), mkExpr( arg3 )->acceptMutator( *visitor ) );
501                                ret->env = expr->env;
502                                expr->env = nullptr;
503                                delete expr;
504
505                                // conditional expr type may not be either of the argument types, need to unify
506                                using namespace ResolvExpr;
507                                Type* commonType = nullptr;
508                                TypeEnvironment newEnv;
509                                AssertionSet needAssertions, haveAssertions;
510                                OpenVarSet openVars;
511                                unify( ret->arg2->result, ret->arg3->result, newEnv, needAssertions, haveAssertions, openVars, SymTab::Indexer(), commonType );
512                                ret->result = commonType ? commonType : ret->arg2->result->clone();
513                                return ret;
514                        }
515                        return expr;
516                }
517
518                Expression * GeneralizedLvalue::postmutate( MemberExpr * memExpr ) {
519                        return applyTransformation( memExpr, memExpr->aggregate, [=]( Expression * aggr ) { return new MemberExpr( memExpr->member, aggr ); } );
520                }
521
522                Expression * GeneralizedLvalue::postmutate( AddressExpr * addrExpr ) {
523                        return applyTransformation( addrExpr, addrExpr->arg, []( Expression * arg ) { return new AddressExpr( arg ); } );
524                }
525
526                Expression * CollapseAddrDeref::postmutate( AddressExpr * addrExpr ) {
527                        Expression * arg = addrExpr->arg;
528                        if ( isIntrinsicReference( arg ) ) {
529                                std::string fname = InitTweak::getFunctionName( arg );
530                                if ( fname == "*?" ) {
531                                        Expression *& arg0 = InitTweak::getCallArg( arg, 0 );
532                                        Expression * ret = arg0;
533                                        ret->set_env( addrExpr->env );
534                                        arg0 = nullptr;
535                                        addrExpr->env = nullptr;
536                                        delete addrExpr;
537                                        return ret;
538                                }
539                        } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( arg ) ) {
540                                // need to move cast to pointer type out a level since address of pointer
541                                // is not valid C code (can be introduced in prior passes, e.g., InstantiateGeneric)
542                                if ( InitTweak::getPointerBase( castExpr->result ) ) {
543                                        addrExpr->arg = castExpr->arg;
544                                        castExpr->arg = addrExpr;
545                                        castExpr->result = new PointerType( Type::Qualifiers(), castExpr->result );
546                                        return castExpr;
547                                }
548                        }
549                        return addrExpr;
550                }
551
552                Expression * CollapseAddrDeref::postmutate( ApplicationExpr * appExpr ) {
553                        if ( isIntrinsicReference( appExpr ) ) {
554                                std::string fname = InitTweak::getFunctionName( appExpr );
555                                if ( fname == "*?" ) {
556                                        Expression * arg = InitTweak::getCallArg( appExpr, 0 );
557                                        // xxx - this isn't right, because it can remove casts that should be there...
558                                        // while ( CastExpr * castExpr = dynamic_cast< CastExpr * >( arg ) ) {
559                                        //      arg = castExpr->get_arg();
560                                        // }
561                                        if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( arg ) ) {
562                                                Expression * ret = addrExpr->arg;
563                                                ret->env = appExpr->env;
564                                                addrExpr->arg = nullptr;
565                                                appExpr->env = nullptr;
566                                                delete appExpr;
567                                                return ret;
568                                        }
569                                }
570                        }
571                        return appExpr;
572                }
573        } // namespace
574} // namespace GenPoly
575
576// Local Variables: //
577// tab-width: 4 //
578// mode: c++ //
579// compile-command: "make install" //
580// End: //
Note: See TracBrowser for help on using the repository browser.