source: src/GenPoly/Lvalue.cc @ 427854b

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 427854b was 427854b, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

First draft implementation of generators, still missing error checking, testing and clean-up

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