source: src/AST/Expr.cpp @ ae265b5

arm-ehjacob/cs343-translationnew-astnew-ast-unique-expr
Last change on this file since ae265b5 was ae265b5, checked in by Michael Brooks <mlbrooks@…>, 2 years ago

Two fixes of MemberExpr? handling on new-AST.

Each bug on its own, and also both bugs together, produce the same symptom: Expressions that use function-pointer typed members of structs, where the function has a generically-typed argument, were lacking casts (vs old-AST) in the output of:

./driver/cfa-cpp --prelude-dir ./libcfa/x64-debug/prelude -tm ../cfa-cc/libcfa/prelude/bootloader.cf bootloader.c

First bug: a conversion inaccuracy, which is a regression of convert-convert-post-resolve, introduced at Jun 28 rev 55b647. The constructor of a MemberExpr?, that Convert old-to-new uses, does type-variable substitution. This is intended behaviour when it occurs during resolve, but is incorrect when done twice. In absence of this fix, the old-to-new converter runs this substitution a second time, both in: oldresolve-old2new-new2old and old2new-newresolve-new2old. The fix is offering/using a no-op constructor to/at the converter.

Second bug: a mutation of a transitively-multiply-referenced object. The type-variable substitution just mentioned, which should be happening to the result type of the MemberExpr? and not to the top-level struct-member declaration, actually happens as:

  • old ast: as should; all type-value intentions are clones
  • new ast pre this fix: incorrectly to both types; ref-counted sharing means theExpr.result == theDecl.type, substitution happens on sub-object (see details in code comment)
  • new ast with this fix: as should; deep copy of the type is explicitly forced upfront

All bootloader output differences (new-AST's resolver vs old-AST's resolver) that remain after this fix are: four constructor-destructor calls in builtin function bodies, and a missing copy-constructor call on invoke-main. These differences were present ahead of this change.

This change has been tested for a clean convert-convert difference (vs no new-AST at all), for convert-convert at: pre-resolve, post-resolve, post-parse. In the case of cvcv post-resolve, this clean difference is being restored from the first-bug regression.

This change has been tested for, and causes a small-to-questionable regression of, cfa-cpp speed of compiling bootloader. Old AST = 6.04 s, New AST before this change = 4.64 s, New ast after this change 4.76 s. All numbers are mean of 5 samples with sample SD ~= 0.3 sec. New-AST improvement before this fix = 23% = 4.2 SDs. New-AST improvement after this fix = 21% = 3.9 SDs.

  • Property mode set to 100644
File size: 13.2 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// Expr.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed May 15 17:00:00 2019
11// Last Modified By : Andrew Beach
12// Created On       : Thr Jun 13 13:38:00 2019
13// Update Count     : 2
14//
15
16#include "Expr.hpp"
17
18#include <cassert>                 // for strict_dynamic_cast
19#include <string>                  // for to_string
20#include <vector>
21
22#include "Copy.hpp"                // for shallowCopy
23#include "Eval.hpp"                // for call
24#include "GenericSubstitution.hpp"
25#include "Stmt.hpp"
26#include "Type.hpp"
27#include "TypeSubstitution.hpp"
28#include "Common/utility.h"
29#include "Common/SemanticError.h"
30#include "GenPoly/Lvalue.h"        // for referencesPermissable
31#include "InitTweak/InitTweak.h"   // for getPointerBase
32#include "ResolvExpr/typeops.h"    // for extractResultType
33#include "Tuples/Tuples.h"         // for makeTupleType
34
35namespace ast {
36
37// --- ApplicationExpr
38
39ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f,
40        std::vector<ptr<Expr>> && as )
41: Expr( loc ), func( f ), args( std::move(as) ) {
42        // ensure that `ApplicationExpr` result type is `FuncExpr`
43        const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() );
44        const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() );
45
46        result = ResolvExpr::extractResultType( fn );
47        assert( result );
48}
49
50// --- UntypedExpr
51
52UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, Expr * arg ) {
53        assert( arg );
54
55        UntypedExpr * ret = call( loc, "*?", arg );
56        if ( const Type * ty = arg->result ) {
57                const Type * base = InitTweak::getPointerBase( ty );
58                assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() );
59
60                if ( GenPoly::referencesPermissable() ) {
61                        // if references are still allowed in the AST, dereference returns a reference
62                        ret->result = new ReferenceType{ base };
63                } else {
64                        // references have been removed, in which case dereference returns an lvalue of the
65                        // base type
66                        ret->result = base;
67                        add_qualifiers( ret->result, CV::Lvalue );
68                }
69        }
70        return ret;
71}
72
73UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, Expr * lhs, Expr * rhs ) {
74        assert( lhs && rhs );
75
76        UntypedExpr * ret = call( loc, "?=?", lhs, rhs );
77        if ( lhs->result && rhs->result ) {
78                // if both expressions are typed, assumes that this assignment is a C bitwise assignment,
79                // so the result is the type of the RHS
80                ret->result = rhs->result;
81        }
82        return ret;
83}
84
85// --- AddressExpr
86
87// Address expressions are typed based on the following inference rules:
88//    E : lvalue T  &..& (n references)
89//   &E :        T *&..& (n references)
90//
91//    E : T  &..&        (m references)
92//   &E : T *&..&        (m-1 references)
93
94namespace {
95        /// The type of the address of a type.
96        /// Caller is responsible for managing returned memory
97        Type * addrType( const Type * type ) {
98                if ( const ReferenceType * refType = dynamic_cast< const ReferenceType * >( type ) ) {
99                        return new ReferenceType{ addrType( refType->base ), refType->qualifiers };
100                } else {
101                        return new PointerType{ type };
102                }
103        }
104}
105
106AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) : Expr( loc ), arg( a ) {
107        if ( arg->result ) {
108                if ( arg->result->is_lvalue() ) {
109                        // lvalue, retains all levels of reference, and gains a pointer inside the references
110                        Type * res = addrType( arg->result );
111                        res->set_lvalue( false ); // result of & is never an lvalue
112                        result = res;
113                } else {
114                        // taking address of non-lvalue, must be a reference, loses one layer of reference
115                        if ( const ReferenceType * refType =
116                                        dynamic_cast< const ReferenceType * >( arg->result.get() ) ) {
117                                Type * res = addrType( refType->base );
118                                res->set_lvalue( false ); // result of & is never an lvalue
119                                result = res;
120                        } else {
121                                SemanticError( loc, arg->result.get(),
122                                        "Attempt to take address of non-lvalue expression: " );
123                        }
124                }
125        }
126}
127
128// --- LabelAddressExpr
129
130// label address always has type `void*`
131LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a )
132: Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {}
133
134// --- CastExpr
135
136CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g )
137: Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ) {}
138
139// --- KeywordCastExpr
140
141const std::string & KeywordCastExpr::targetString() const {
142        static const std::string targetStrs[] = {
143                "coroutine", "thread", "monitor"
144        };
145        static_assert(
146                (sizeof(targetStrs) / sizeof(targetStrs[0])) == ((unsigned long)NUMBER_OF_TARGETS),
147                "Each KeywordCastExpr::Target should have a corresponding string representation"
148        );
149        return targetStrs[(unsigned long)target];
150}
151
152// --- MemberExpr
153
154MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg )
155: Expr( loc ), member( mem ), aggregate( agg ) {
156        assert( member );
157        assert( aggregate );
158        assert( aggregate->result );
159
160        // Deep copy on result type avoids mutation on transitively multiply referenced object.
161        //
162        // Example, adapted from parts of builtins and bootloader:
163        //
164        // forall(dtype T)
165        // struct __Destructor {
166        //   T * object;
167        //   void (*dtor)(T *);
168        // };
169        //
170        // forall(dtype S)
171        // void foo(__Destructor(S) &d) {
172        //   if (d.dtor) {  // here
173        //   }
174        // }
175        //
176        // Let e be the "d.dtor" guard espression, which is MemberExpr after resolve.  Let d be the
177        // declaration of member __Destructor.dtor (an ObjectDecl), as accessed via the top-level
178        // declaration of __Destructor.  Consider the types e.result and d.type.  In the old AST, one
179        // is a clone of the other.  Ordinary new-AST use would set them up as a multiply-referenced
180        // object.
181        //
182        // e.result: PointerType
183        // .base: FunctionType
184        // .params.front(): ObjectDecl, the anonymous parameter of type T*
185        // .type: PointerType
186        // .base: TypeInstType
187        // let x = that
188        // let y = similar, except start from d.type
189        //
190        // Consider two code lines down, genericSubstitution(...).apply(result).
191        //
192        // Applying this chosen-candidate's type substitution means modifying x, substituting
193        // S for T.  This mutation should affect x and not y.
194
195        result = deepCopy(mem->get_type());
196
197        // substitute aggregate generic parameters into member type
198        genericSubstitution( aggregate->result ).apply( result );
199        // ensure lvalue and appropriate restrictions from aggregate type
200        add_qualifiers( result, aggregate->result->qualifiers | CV::Lvalue );
201}
202
203MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg,
204    MemberExpr::NoOpConstruction overloadSelector )
205: Expr( loc ), member( mem ), aggregate( agg ) {
206        assert( member );
207        assert( aggregate );
208        assert( aggregate->result );
209        (void) overloadSelector;
210}
211
212// --- VariableExpr
213
214VariableExpr::VariableExpr( const CodeLocation & loc )
215: Expr( loc ), var( nullptr ) {}
216
217VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v )
218: Expr( loc ), var( v ) {
219        assert( var );
220        assert( var->get_type() );
221        auto r = shallowCopy( var->get_type() );
222        r->qualifiers |= CV::Lvalue;
223        result = r;
224}
225
226VariableExpr * VariableExpr::functionPointer(
227                const CodeLocation & loc, const FunctionDecl * decl ) {
228        // wrap usually-determined result type in a pointer
229        VariableExpr * funcExpr = new VariableExpr{ loc, decl };
230        funcExpr->result = new PointerType{ funcExpr->result };
231        return funcExpr;
232}
233
234// --- ConstantExpr
235
236long long int ConstantExpr::intValue() const {
237        if ( const BasicType * bty = result.as< BasicType >() ) {
238                if ( bty->isInteger() ) {
239                        assert(ival);
240                        return ival.value();
241                }
242        } else if ( result.as< ZeroType >() ) {
243                return 0;
244        } else if ( result.as< OneType >() ) {
245                return 1;
246        }
247        SemanticError( this, "Constant expression of non-integral type " );
248}
249
250ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
251        return new ConstantExpr{
252                loc, new BasicType{ BasicType::Bool }, b ? "1" : "0", (unsigned long long)b };
253}
254
255ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
256        return new ConstantExpr{
257                loc, new BasicType{ BasicType::SignedInt }, std::to_string( i ), (unsigned long long)i };
258}
259
260ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
261        return new ConstantExpr{
262                loc, new BasicType{ BasicType::LongUnsignedInt }, std::to_string( i ),
263                (unsigned long long)i };
264}
265
266ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) {
267        return new ConstantExpr{
268                loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 };
269}
270
271// --- SizeofExpr
272
273SizeofExpr::SizeofExpr( const CodeLocation & loc, const Expr * e )
274: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
275
276SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * t )
277: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
278
279// --- AlignofExpr
280
281AlignofExpr::AlignofExpr( const CodeLocation & loc, const Expr * e )
282: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( e ), type( nullptr ) {}
283
284AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * t )
285: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), expr( nullptr ), type( t ) {}
286
287// --- OffsetofExpr
288
289OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem )
290: Expr( loc, new BasicType{ BasicType::LongUnsignedInt } ), type( ty ), member( mem ) {
291        assert( type );
292        assert( member );
293}
294
295// --- OffsetPackExpr
296
297OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty )
298: Expr( loc, new ArrayType{
299        new BasicType{ BasicType::LongUnsignedInt }, nullptr, FixedLen, DynamicDim }
300), type( ty ) {
301        assert( type );
302}
303
304// --- LogicalExpr
305
306LogicalExpr::LogicalExpr(
307        const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
308: Expr( loc, new BasicType{ BasicType::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
309
310// --- ConstructorExpr
311
312ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call )
313: Expr( loc ), callExpr( call ) {
314        // allow resolver to type a constructor used as an expression if it has the same type as its
315        // first argument
316        assert( callExpr );
317        const Expr * arg = InitTweak::getCallArg( callExpr, 0 );
318        assert( arg );
319        result = arg->result;
320}
321
322// --- CompoundLiteralExpr
323
324CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i )
325: Expr( loc ), init( i ) {
326        assert( t && i );
327        result = t;
328        add_qualifiers( result, CV::Lvalue );
329}
330
331// --- TupleExpr
332
333TupleExpr::TupleExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && xs )
334: Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {}
335
336// --- TupleIndexExpr
337
338TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i )
339: Expr( loc ), tuple( t ), index( i ) {
340        const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() );
341        assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested "
342                "index %d in expr %s", type->size(), index, toString( tuple ).c_str() );
343        // like MemberExpr, TupleIndexExpr is always an lvalue
344        result = type->types[ index ];
345        add_qualifiers( result, CV::Lvalue );
346}
347
348// --- TupleAssignExpr
349
350TupleAssignExpr::TupleAssignExpr(
351        const CodeLocation & loc, std::vector<ptr<Expr>> && assigns,
352        std::vector<ptr<ObjectDecl>> && tempDecls )
353: Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() {
354        // convert internally into a StmtExpr which contains the declarations and produces the tuple of
355        // the assignments
356        std::list<ptr<Stmt>> stmts;
357        for ( const ObjectDecl * obj : tempDecls ) {
358                stmts.emplace_back( new DeclStmt{ loc, obj } );
359        }
360        TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) };
361        assert( tupleExpr->result );
362        stmts.emplace_back( new ExprStmt{ loc, tupleExpr } );
363        stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } };
364}
365
366TupleAssignExpr::TupleAssignExpr(
367        const CodeLocation & loc, const Type * result, const StmtExpr * s )
368: Expr( loc, result ), stmtExpr() {
369        stmtExpr = s;
370}
371
372// --- StmtExpr
373
374StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss )
375: Expr( loc ), stmts( ss ), returnDecls(), dtors() { computeResult(); }
376
377void StmtExpr::computeResult() {
378        assert( stmts );
379        const std::list<ptr<Stmt>> & body = stmts->kids;
380        if ( ! returnDecls.empty() ) {
381                // prioritize return decl for result type, since if a return decl exists, then the StmtExpr
382                // is currently in an intermediate state where the body will always give a void result type
383                result = returnDecls.front()->get_type();
384        } else if ( ! body.empty() ) {
385                if ( const ExprStmt * exprStmt = body.back().as< ExprStmt >() ) {
386                        result = exprStmt->expr->result;
387                }
388        }
389        // ensure a result type exists
390        if ( ! result ) { result = new VoidType{}; }
391}
392
393// --- UniqueExpr
394
395unsigned long long UniqueExpr::nextId = 0;
396
397UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i )
398: Expr( loc, e->result ), expr( e ), id( i ) {
399        assert( expr );
400        if ( id == -1ull ) {
401                assert( nextId != -1ull );
402                id = nextId++;
403        }
404}
405
406}
407
408// Local Variables: //
409// tab-width: 4 //
410// mode: c++ //
411// compile-command: "make install" //
412// End: //
Note: See TracBrowser for help on using the repository browser.