source: src/GenPoly/Lvalue.cc@ 207b496

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum with_gc
Last change on this file since 207b496 was 207b496, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Update FixIntrinsicArgs conditions (not quite correct)

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