source: src/GenPoly/Lvalue.cc @ 0e398ad

ADTast-experimental
Last change on this file since 0e398ad was 9feb34b, checked in by Andrew Beach <ajbeach@…>, 15 months ago

Moved toString and toCString to a new header. Updated includes. cassert was somehow getting instances of toString before but that stopped working so I embedded the new smaller include.

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