source: src/AST/Expr.cpp@ 9d7a19f

Last change on this file since 9d7a19f was 366f5cd, checked in by Peter A. Buhr <pabuhr@…>, 25 hours ago

differentiate between C _Alignof and gcc alignof

  • Property mode set to 100644
File size: 13.0 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 : Peter A. Buhr
12// Created On : Wed May 18 13:56:00 2022
13// Update Count : 18
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 "GenericSubstitution.hpp"
24#include "Inspect.hpp"
25#include "LinkageSpec.hpp"
26#include "Stmt.hpp"
27#include "Type.hpp"
28#include "TypeSubstitution.hpp"
29#include "Common/Utility.hpp"
30#include "Common/SemanticError.hpp"
31#include "GenPoly/Lvalue.hpp" // for referencesPermissable
32#include "ResolvExpr/Unify.hpp" // for extractResultType
33#include "Tuples/Tuples.hpp" // for makeTupleType
34
35namespace ast {
36
37namespace {
38 std::set<std::string> const lvalueFunctionNames = {"*?", "?[?]"};
39}
40
41// --- Expr
42bool Expr::get_lvalue() const {
43 return false;
44}
45
46// --- ApplicationExpr
47
48ApplicationExpr::ApplicationExpr( const CodeLocation & loc, const Expr * f, std::vector<ptr<Expr>> && as )
49 : Expr( loc ), func( f ), args( std::move(as) ) {
50 // ensure that `ApplicationExpr` result type is `FuncExpr`
51 const PointerType * pt = strict_dynamic_cast< const PointerType * >( f->result.get() );
52 const FunctionType * fn = strict_dynamic_cast< const FunctionType * >( pt->base.get() );
53
54 result = ResolvExpr::extractResultType( fn );
55 assert( result );
56}
57
58bool ApplicationExpr::get_lvalue() const {
59 if ( const DeclWithType * func = getFunction( this ) ) {
60 return func->linkage == Linkage::Intrinsic && lvalueFunctionNames.count( func->name );
61 }
62 return false;
63}
64
65// --- UntypedExpr
66
67bool UntypedExpr::get_lvalue() const {
68 std::string fname = getFunctionName( this );
69 return lvalueFunctionNames.count( fname );
70}
71
72UntypedExpr * UntypedExpr::createDeref( const CodeLocation & loc, const Expr * arg ) {
73 assert( arg );
74
75 UntypedExpr * ret = createCall( loc, "*?", { arg } );
76 if ( const Type * ty = arg->result ) {
77 const Type * base = getPointerBase( ty );
78 assertf( base, "expected pointer type in dereference (type was %s)", toString( ty ).c_str() );
79
80 if ( GenPoly::referencesPermissable() ) {
81 // if references are still allowed in the AST, dereference returns a reference
82 ret->result = new ReferenceType{ base };
83 } else {
84 // references have been removed, in which case dereference returns an lvalue of the
85 // base type
86 ret->result = base;
87 }
88 }
89 return ret;
90}
91
92UntypedExpr * UntypedExpr::createAssign( const CodeLocation & loc, const Expr * lhs, const Expr * rhs ) {
93 assert( lhs && rhs );
94
95 UntypedExpr * ret = createCall( loc, "?=?", { lhs, rhs } );
96 if ( lhs->result && rhs->result ) {
97 // if both expressions are typed, assumes that this assignment is a C bitwise assignment,
98 // so the result is the type of the RHS
99 ret->result = rhs->result;
100 }
101 return ret;
102}
103
104UntypedExpr * UntypedExpr::createCall( const CodeLocation & loc, const std::string & name, std::vector<ptr<Expr>> && args ) {
105 return new UntypedExpr( loc,
106 new NameExpr( loc, name ), std::move( args ) );
107}
108
109// --- VariableExpr
110
111VariableExpr::VariableExpr( const CodeLocation & loc ) : Expr( loc ), var( nullptr ) {}
112
113VariableExpr::VariableExpr( const CodeLocation & loc, const DeclWithType * v ) : Expr( loc ), var( v ) {
114 assert( var );
115 assert( var->get_type() );
116 result = shallowCopy( var->get_type() );
117}
118
119bool VariableExpr::get_lvalue() const {
120 // Special case for enumeration labels (more literals than variables):
121 if(dynamic_cast<const ast::EnumInstType *>(var->get_type())) return !var->isMember;
122 // The remaining uses are either actual variables (lvalues) or function
123 // names which are a special value catagory that can be treated as
124 // lvalues in the places we are worried about.
125 return true;
126}
127
128VariableExpr * VariableExpr::functionPointer( const CodeLocation & loc, const FunctionDecl * decl ) {
129 // wrap usually-determined result type in a pointer
130 VariableExpr * funcExpr = new VariableExpr{ loc, decl };
131 funcExpr->result = new PointerType{ funcExpr->result };
132 return funcExpr;
133}
134
135// --- AddressExpr
136
137// Address expressions are typed based on the following inference rules:
138// E : lvalue T &..& (n references)
139// &E : T *&..& (n references)
140//
141// E : T &..& (m references)
142// &E : T *&..& (m-1 references)
143
144namespace {
145 /// The type of the address of a type.
146 /// Caller is responsible for managing returned memory
147 Type * addrType( const ptr<Type> & type ) {
148 if ( auto refType = type.as< ReferenceType >() ) {
149 return new ReferenceType( addrType( refType->base ), refType->qualifiers );
150 } else {
151 return new PointerType( type );
152 }
153 }
154
155 /// The type of the address of an expression.
156 /// Caller is responsible for managing returned memory
157 Type * addrExprType( const CodeLocation & loc, const Expr * arg ) {
158 assert( arg );
159 // If the expression's type is unknown, the address type is unknown.
160 if ( nullptr == arg->result ) {
161 return nullptr;
162 // An lvalue is transformed directly.
163 } else if ( arg->get_lvalue() ) {
164 return addrType( arg->result );
165 // Strip a layer of reference to "create" an lvalue expression.
166 } else if ( auto refType = arg->result.as< ReferenceType >() ) {
167 return addrType( refType->base );
168 } else {
169 SemanticError( loc, "Attempt to take address of non-lvalue expression %s",
170 toString( arg->result.get() ).c_str() );
171 }
172 }
173}
174
175AddressExpr::AddressExpr( const CodeLocation & loc, const Expr * a ) : Expr( loc, addrExprType( loc, a ) ), arg( a ) {}
176
177// --- LabelAddressExpr
178
179// label address always has type `void*`
180LabelAddressExpr::LabelAddressExpr( const CodeLocation & loc, Label && a )
181: Expr( loc, new PointerType{ new VoidType{} } ), arg( a ) {}
182
183// --- CastExpr
184
185CastExpr::CastExpr( const CodeLocation & loc, const Expr * a, GeneratedFlag g, CastKind kind )
186 : Expr( loc, new VoidType{} ), arg( a ), isGenerated( g ), kind( kind ) {}
187
188bool CastExpr::get_lvalue() const {
189 // This is actually wrong by C, but it works with our current set-up.
190 return arg->get_lvalue();
191}
192
193// --- KeywordCastExpr
194
195const char * KeywordCastExpr::targetString() const {
196 return AggregateDecl::aggrString( target );
197}
198
199// --- UntypedMemberExpr
200
201bool UntypedMemberExpr::get_lvalue() const {
202 return aggregate->get_lvalue();
203}
204
205// --- MemberExpr
206
207MemberExpr::MemberExpr( const CodeLocation & loc, const DeclWithType * mem, const Expr * agg )
208 : Expr( loc ), member( mem ), aggregate( agg ) {
209 assert( member );
210 assert( aggregate );
211 assert( aggregate->result );
212
213 result = mem->get_type();
214
215 // substitute aggregate generic parameters into member type
216 genericSubstitution( aggregate->result ).apply( result );
217 // ensure appropriate restrictions from aggregate type
218 add_qualifiers( result, aggregate->result->qualifiers );
219}
220
221bool MemberExpr::get_lvalue() const {
222 // This is actually wrong by C, but it works with our current set-up.
223 return true;
224}
225
226// --- ConstantExpr
227
228long long int ConstantExpr::intValue() const {
229 if ( const BasicType * bty = result.as< BasicType >() ) {
230 if ( bty->isInteger() ) {
231 assert(ival);
232 return ival.value();
233 }
234 } else if ( result.as< ZeroType >() ) {
235 return 0;
236 } else if ( result.as< OneType >() ) {
237 return 1;
238 }
239 SemanticError( this->location, "Constant expression of non-integral type %s",
240 toString( this ).c_str() );
241}
242
243ConstantExpr * ConstantExpr::from_bool( const CodeLocation & loc, bool b ) {
244 return new ConstantExpr{ loc, new BasicType{ BasicKind::Bool }, b ? "1" : "0", (unsigned long long)b };
245}
246
247ConstantExpr * ConstantExpr::from_int( const CodeLocation & loc, int i ) {
248 return new ConstantExpr{ loc, new BasicType{ BasicKind::SignedInt }, std::to_string( i ), (unsigned long long)i };
249}
250
251ConstantExpr * ConstantExpr::from_ulong( const CodeLocation & loc, unsigned long i ) {
252 return new ConstantExpr{ loc, new BasicType{ BasicKind::LongUnsignedInt }, std::to_string( i ), (unsigned long long)i };
253}
254
255ConstantExpr * ConstantExpr::from_string( const CodeLocation & loc, const std::string & str ) {
256 const Type * charType = new BasicType( BasicKind::Char, ast::CV::Const );
257 // Adjust the length of the string for the terminator.
258 const Expr * strSize = from_ulong( loc, str.size() + 1 );
259 const Type * strType = new ArrayType( charType, strSize, FixedLen, DynamicDim );
260 const std::string strValue = "\"" + str + "\"";
261 return new ConstantExpr( loc, strType, strValue, std::nullopt );
262}
263
264ConstantExpr * ConstantExpr::null( const CodeLocation & loc, const Type * ptrType ) {
265 return new ConstantExpr{ loc, ptrType ? ptrType : new PointerType{ new VoidType{} }, "0", (unsigned long long)0 };
266}
267
268// --- SizeofExpr
269
270SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * type ) : SizeofExpr( loc, type, nullptr ) {}
271
272SizeofExpr::SizeofExpr( const CodeLocation & loc, const Type * type, const Type * result ) : Expr( loc, result ), type( type ) {}
273
274// --- AlignofExpr
275
276AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * type, const Alignment kind ) : AlignofExpr( loc, type, nullptr, kind ) {}
277
278AlignofExpr::AlignofExpr( const CodeLocation & loc, const Type * type, const Type * result, const Alignment kind )
279 : Expr( loc, result ), type( type ), kind( kind ) {}
280
281// --- CountofExpr
282
283CountofExpr::CountofExpr( const CodeLocation & loc, const Type * t ) : Expr( loc ), type( t ) {}
284
285// --- OffsetofExpr
286
287OffsetofExpr::OffsetofExpr( const CodeLocation & loc, const Type * ty, const DeclWithType * mem, const Type * res )
288 : Expr( loc, res ), type( ty ), member( mem ) {
289 assert( type );
290 assert( member );
291}
292
293// --- OffsetPackExpr
294
295OffsetPackExpr::OffsetPackExpr( const CodeLocation & loc, const StructInstType * ty ) : Expr( loc ), type( ty ) {
296 assert( type );
297}
298
299// --- LogicalExpr
300
301LogicalExpr::LogicalExpr( const CodeLocation & loc, const Expr * a1, const Expr * a2, LogicalFlag ia )
302 : Expr( loc, new BasicType{ BasicKind::SignedInt } ), arg1( a1 ), arg2( a2 ), isAnd( ia ) {}
303
304// --- CommaExpr
305
306bool CommaExpr::get_lvalue() const {
307 // This is wrong by C, but the current implementation uses it.
308 // (ex: Specialize, Lvalue and Box)
309 return arg2->get_lvalue();
310}
311
312// --- ConstructorExpr
313
314ConstructorExpr::ConstructorExpr( const CodeLocation & loc, const Expr * call ) : Expr( loc ), callExpr( call ) {
315 // allow resolver to type a constructor used as an expression if it has the same type as its
316 // first argument
317 assert( callExpr );
318 const Expr * arg = getCallArg( callExpr, 0 );
319 assert( arg );
320 result = arg->result;
321}
322
323// --- CompoundLiteralExpr
324
325CompoundLiteralExpr::CompoundLiteralExpr( const CodeLocation & loc, const Type * t, const Init * i ) : Expr( loc ), init( i ) {
326 assert( t && i );
327 result = t;
328}
329
330bool CompoundLiteralExpr::get_lvalue() const {
331 return true;
332}
333
334// --- TupleExpr
335
336TupleExpr::TupleExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && xs ) : Expr( loc, Tuples::makeTupleType( xs ) ), exprs( xs ) {}
337
338// --- TupleIndexExpr
339
340TupleIndexExpr::TupleIndexExpr( const CodeLocation & loc, const Expr * t, unsigned i ) : Expr( loc ), tuple( t ), index( i ) {
341 const TupleType * type = strict_dynamic_cast< const TupleType * >( tuple->result.get() );
342 assertf( type->size() > index, "TupleIndexExpr index out of bounds: tuple size %d, requested "
343 "index %d in expr %s", type->size(), index, toString( tuple ).c_str() );
344 // like MemberExpr, TupleIndexExpr is always an lvalue
345 result = type->types[ index ];
346}
347
348bool TupleIndexExpr::get_lvalue() const {
349 return tuple->get_lvalue();
350}
351
352// --- TupleAssignExpr
353
354TupleAssignExpr::TupleAssignExpr( const CodeLocation & loc, std::vector<ptr<Expr>> && assigns, std::vector<ptr<ObjectDecl>> && tempDecls )
355 : Expr( loc, Tuples::makeTupleType( assigns ) ), stmtExpr() {
356 // convert internally into a StmtExpr which contains the declarations and produces the tuple of
357 // the assignments
358 std::list<ptr<Stmt>> stmts;
359 for ( const ObjectDecl * obj : tempDecls ) {
360 stmts.emplace_back( new DeclStmt{ loc, obj } );
361 }
362 TupleExpr * tupleExpr = new TupleExpr{ loc, std::move(assigns) };
363 assert( tupleExpr->result );
364 stmts.emplace_back( new ExprStmt{ loc, tupleExpr } );
365 stmtExpr = new StmtExpr{ loc, new CompoundStmt{ loc, std::move(stmts) } };
366}
367
368// --- StmtExpr
369
370StmtExpr::StmtExpr( const CodeLocation & loc, const CompoundStmt * ss ) : Expr( loc ), stmts( ss ) { computeResult(); }
371
372void StmtExpr::computeResult() {
373 assert( stmts );
374 const std::list<ptr<Stmt>> & body = stmts->kids;
375 // If there is a tail expression, its result is entire result.
376 if ( !body.empty() && ( resultExpr = body.back().as<ExprStmt>() ) ) {
377 result = resultExpr->expr->result;
378 // Otherwise, fill in the result with void so there is a result type.
379 } else {
380 result = new VoidType();
381 }
382}
383
384// --- UniqueExpr
385
386unsigned long long UniqueExpr::nextId = 0;
387
388UniqueExpr::UniqueExpr( const CodeLocation & loc, const Expr * e, unsigned long long i ) : Expr( loc, e->result ), expr( e ), id( i ) {
389 assert( expr );
390 if ( id == -1ull ) {
391 assert( nextId != -1ull );
392 id = nextId++;
393 }
394}
395
396}
397
398// Local Variables: //
399// tab-width: 4 //
400// mode: c++ //
401// compile-command: "make install" //
402// End: //
Note: See TracBrowser for help on using the repository browser.