source: src/AST/Expr.cpp @ f2d1335

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since f2d1335 was 3f3bfe5a, checked in by Andrew Beach <ajbeach@…>, 5 years ago

Merge from master to new-ast. Removing old lvalue support.

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