source: src/InitTweak/InitTweak.cc@ c4072d8e

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since c4072d8e was 720f2fe2, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Changed 'addDataSectionAttribute' to correctly handle tls.
Fixed Typo.

  • Property mode set to 100644
File size: 47.4 KB
RevLine 
[2d11663]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// InitTweak.cc --
8//
9// Author : Rob Schluntz
10// Created On : Fri May 13 11:26:36 2016
[3cc1111]11// Last Modified By : Andrew Beach
[00a8e19]12// Last Modified On : Mon Dec 6 13:21:00 2021
13// Update Count : 20
[2d11663]14//
15
[d180746]16#include <algorithm> // for find, all_of
[e3e16bc]17#include <cassert> // for assertf, assert, strict_dynamic_cast
[d180746]18#include <iostream> // for ostream, cerr, endl
19#include <iterator> // for back_insert_iterator, back_inserter
20#include <memory> // for __shared_ptr
[2d11663]21#include <vector>
[d180746]22
[9b4f329]23#include "AST/Expr.hpp"
[c1ed2ee]24#include "AST/Init.hpp"
[b8524ca]25#include "AST/Node.hpp"
[c1ed2ee]26#include "AST/Pass.hpp"
[9b4f329]27#include "AST/Stmt.hpp"
[9e1d485]28#include "AST/Type.hpp"
[fd236ed]29#include "Common/PassVisitor.h"
[d180746]30#include "Common/SemanticError.h" // for SemanticError
31#include "Common/UniqueName.h" // for UniqueName
32#include "Common/utility.h" // for toString, deleteAll, maybeClone
33#include "GenPoly/GenPoly.h" // for getFunctionType
[2b46a13]34#include "InitTweak.h"
[d180746]35#include "ResolvExpr/typeops.h" // for typesCompatibleIgnoreQualifiers
[f5c3b6c]36#include "SymTab/Autogen.h"
[d180746]37#include "SymTab/Indexer.h" // for Indexer
[07de76b]38#include "SynTree/LinkageSpec.h" // for Spec, isBuiltin, Intrinsic
[d180746]39#include "SynTree/Attribute.h" // for Attribute
40#include "SynTree/Constant.h" // for Constant
41#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
42#include "SynTree/Expression.h" // for Expression, UntypedExpr, Applicati...
43#include "SynTree/Initializer.h" // for Initializer, ListInit, Designation
[ba3706f]44#include "SynTree/Label.h" // for Label
[d180746]45#include "SynTree/Statement.h" // for CompoundStmt, ExprStmt, BranchStmt
46#include "SynTree/Type.h" // for FunctionType, ArrayType, PointerType
47#include "SynTree/Visitor.h" // for Visitor, maybeAccept
[29bc63e]48#include "Tuples/Tuples.h" // for Tuples::isTtype
[d180746]49
[2b46a13]50namespace InitTweak {
[64071c2]51 namespace {
[1fbeebd]52 struct HasDesignations : public WithShortCircuiting {
[64071c2]53 bool hasDesignations = false;
[fd236ed]54
55 void previsit( BaseSyntaxNode * ) {
56 // short circuit if we already know there are designations
57 if ( hasDesignations ) visit_children = false;
58 }
59
60 void previsit( Designation * des ) {
61 // short circuit if we already know there are designations
62 if ( hasDesignations ) visit_children = false;
63 else if ( ! des->get_designators().empty() ) {
64 hasDesignations = true;
65 visit_children = false;
66 }
[64071c2]67 }
68 };
[2b46a13]69
[ef3d798]70 struct InitDepthChecker : public WithGuards {
[dcd73d1]71 bool depthOkay = true;
72 Type * type;
73 int curDepth = 0, maxDepth = 0;
74 InitDepthChecker( Type * type ) : type( type ) {
75 Type * t = type;
76 while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
77 maxDepth++;
78 t = at->get_base();
79 }
80 maxDepth++;
81 }
[ef3d798]82 void previsit( ListInit * ) {
[dcd73d1]83 curDepth++;
[ef3d798]84 GuardAction( [this]() { curDepth--; } );
[dcd73d1]85 if ( curDepth > maxDepth ) depthOkay = false;
86 }
87 };
88
[16ba4a6f]89 struct HasDesignations_new : public ast::WithShortCircuiting {
90 bool result = false;
91
92 void previsit( const ast::Node * ) {
93 // short circuit if we already know there are designations
94 if ( result ) visit_children = false;
95 }
96
97 void previsit( const ast::Designation * des ) {
98 // short circuit if we already know there are designations
99 if ( result ) visit_children = false;
100 else if ( ! des->designators.empty() ) {
101 result = true;
102 visit_children = false;
103 }
104 }
105 };
106
107 struct InitDepthChecker_new : public ast::WithGuards {
108 bool result = true;
109 const ast::Type * type;
110 int curDepth = 0, maxDepth = 0;
111 InitDepthChecker_new( const ast::Type * type ) : type( type ) {
112 const ast::Type * t = type;
113 while ( auto at = dynamic_cast< const ast::ArrayType * >( t ) ) {
114 maxDepth++;
115 t = at->base;
116 }
117 maxDepth++;
118 }
119 void previsit( ListInit * ) {
120 curDepth++;
121 GuardAction( [this]() { curDepth--; } );
122 if ( curDepth > maxDepth ) result = false;
123 }
124 };
125
[c1ed2ee]126 struct InitFlattener_old : public WithShortCircuiting {
[c3f551b]127 void previsit( SingleInit * singleInit ) {
128 visit_children = false;
129 argList.push_back( singleInit->value->clone() );
130 }
[64071c2]131 std::list< Expression * > argList;
132 };
[2b46a13]133
[c1ed2ee]134 struct InitFlattener_new : public ast::WithShortCircuiting {
135 std::vector< ast::ptr< ast::Expr > > argList;
136
137 void previsit( const ast::SingleInit * singleInit ) {
138 visit_children = false;
139 argList.emplace_back( singleInit->value );
140 }
141 };
142
143 } // anonymous namespace
[2b46a13]144
[64071c2]145 std::list< Expression * > makeInitList( Initializer * init ) {
[c1ed2ee]146 PassVisitor<InitFlattener_old> flattener;
[4d2434a]147 maybeAccept( init, flattener );
[c3f551b]148 return flattener.pass.argList;
[64071c2]149 }
[2b46a13]150
[64071c2]151 bool isDesignated( Initializer * init ) {
[fd236ed]152 PassVisitor<HasDesignations> finder;
[64071c2]153 maybeAccept( init, finder );
[fd236ed]154 return finder.pass.hasDesignations;
[dcd73d1]155 }
156
157 bool checkInitDepth( ObjectDecl * objDecl ) {
[ef3d798]158 PassVisitor<InitDepthChecker> checker( objDecl->type );
159 maybeAccept( objDecl->init, checker );
160 return checker.pass.depthOkay;
[64071c2]161 }
[2b46a13]162
[16ba4a6f]163 bool isDesignated( const ast::Init * init ) {
164 ast::Pass<HasDesignations_new> finder;
165 maybe_accept( init, finder );
166 return finder.core.result;
167 }
168
169 bool checkInitDepth( const ast::ObjectDecl * objDecl ) {
170 ast::Pass<InitDepthChecker_new> checker( objDecl->type );
171 maybe_accept( objDecl->init.get(), checker );
172 return checker.core.result;
173 }
174
[b8524ca]175std::vector< ast::ptr< ast::Expr > > makeInitList( const ast::Init * init ) {
[c1ed2ee]176 ast::Pass< InitFlattener_new > flattener;
177 maybe_accept( init, flattener );
[7ff3e522]178 return std::move( flattener.core.argList );
[b8524ca]179}
180
181 class InitExpander_old::ExpanderImpl {
[39f84a4]182 public:
[3351cc0]183 virtual ~ExpanderImpl() = default;
[39f84a4]184 virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
[4d2434a]185 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
[39f84a4]186 };
187
[b8524ca]188 class InitImpl_old : public InitExpander_old::ExpanderImpl {
[39f84a4]189 public:
[b8524ca]190 InitImpl_old( Initializer * init ) : init( init ) {}
191 virtual ~InitImpl_old() = default;
[39f84a4]192
[7e003011]193 virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
[39f84a4]194 // this is wrong, but just a placeholder for now
[4d2434a]195 // if ( ! flattened ) flatten( indices );
196 // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
197 return makeInitList( init );
[39f84a4]198 }
[4d2434a]199
200 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]201 private:
[4d2434a]202 Initializer * init;
[39f84a4]203 };
204
[b8524ca]205 class ExprImpl_old : public InitExpander_old::ExpanderImpl {
[39f84a4]206 public:
[b8524ca]207 ExprImpl_old( Expression * expr ) : arg( expr ) {}
208 virtual ~ExprImpl_old() { delete arg; }
[9b4c936]209
[39f84a4]210 virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
211 std::list< Expression * > ret;
212 Expression * expr = maybeClone( arg );
213 if ( expr ) {
214 for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
215 // go through indices and layer on subscript exprs ?[?]
216 ++it;
217 UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
218 subscriptExpr->get_args().push_back( expr );
219 subscriptExpr->get_args().push_back( (*it)->clone() );
220 expr = subscriptExpr;
221 }
222 ret.push_back( expr );
223 }
224 return ret;
225 }
[4d2434a]226
227 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
[39f84a4]228 private:
229 Expression * arg;
230 };
231
[b8524ca]232 InitExpander_old::InitExpander_old( Initializer * init ) : expander( new InitImpl_old( init ) ) {}
[39f84a4]233
[b8524ca]234 InitExpander_old::InitExpander_old( Expression * expr ) : expander( new ExprImpl_old( expr ) ) {}
[39f84a4]235
[b8524ca]236 std::list< Expression * > InitExpander_old::operator*() {
[39f84a4]237 return cur;
238 }
239
[b8524ca]240 InitExpander_old & InitExpander_old::operator++() {
[39f84a4]241 cur = expander->next( indices );
242 return *this;
243 }
244
245 // use array indices list to build switch statement
[b8524ca]246 void InitExpander_old::addArrayIndex( Expression * index, Expression * dimension ) {
[39f84a4]247 indices.push_back( index );
248 indices.push_back( dimension );
249 }
250
[b8524ca]251 void InitExpander_old::clearArrayIndices() {
[9b4c936]252 deleteAll( indices );
[4d2434a]253 indices.clear();
[1a5ad8c]254 }
255
[b8524ca]256 bool InitExpander_old::addReference() {
[1a5ad8c]257 bool added = false;
258 for ( Expression *& expr : cur ) {
259 expr = new AddressExpr( expr );
260 added = true;
261 }
262 return added;
[4d2434a]263 }
264
265 namespace {
[f9cebb5]266 /// given index i, dimension d, initializer init, and callExpr f, generates
267 /// if (i < d) f(..., init)
268 /// ++i;
269 /// so that only elements within the range of the array are constructed
[4d2434a]270 template< typename OutIterator >
[f9cebb5]271 void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
[4d2434a]272 UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
273 cond->get_args().push_back( index->clone() );
274 cond->get_args().push_back( dimension->clone() );
275
276 std::list< Expression * > args = makeInitList( init );
277 callExpr->get_args().splice( callExpr->get_args().end(), args );
278
[ba3706f]279 *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
[4d2434a]280
281 UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
[175ad32b]282 increment->get_args().push_back( index->clone() );
[ba3706f]283 *out++ = new ExprStmt( increment );
[4d2434a]284 }
285
286 template< typename OutIterator >
[b8524ca]287 void build( UntypedExpr * callExpr, InitExpander_old::IndexList::iterator idx, InitExpander_old::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
[4d2434a]288 if ( idx == idxEnd ) return;
289 Expression * index = *idx++;
290 assert( idx != idxEnd );
291 Expression * dimension = *idx++;
292
[f9cebb5]293 // xxx - may want to eventually issue a warning here if we can detect
294 // that the number of elements exceeds to dimension of the array
[4d2434a]295 if ( idx == idxEnd ) {
296 if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
297 for ( Initializer * init : *listInit ) {
[f9cebb5]298 buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]299 }
300 } else {
[f9cebb5]301 buildCallExpr( callExpr->clone(), index, dimension, init, out );
[4d2434a]302 }
303 } else {
304 std::list< Statement * > branches;
305
306 unsigned long cond = 0;
307 ListInit * listInit = dynamic_cast< ListInit * >( init );
308 if ( ! listInit ) {
309 // xxx - this shouldn't be an error, but need a way to
310 // terminate without creating output, so should catch this error
[a16764a6]311 SemanticError( init->location, "unbalanced list initializers" );
[4d2434a]312 }
[f9cebb5]313
314 static UniqueName targetLabel( "L__autogen__" );
315 Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
[4d2434a]316 for ( Initializer * init : *listInit ) {
317 Expression * condition;
318 // check for designations
319 // if ( init-> ) {
320 condition = new ConstantExpr( Constant::from_ulong( cond ) );
321 ++cond;
322 // } else {
323 // condition = // ... take designation
324 // cond = // ... take designation+1
325 // }
326 std::list< Statement * > stmts;
327 build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
[ba3706f]328 stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
329 CaseStmt * caseStmt = new CaseStmt( condition, stmts );
[4d2434a]330 branches.push_back( caseStmt );
331 }
[ba3706f]332 *out++ = new SwitchStmt( index->clone(), branches );
333 *out++ = new NullStmt( { switchLabel } );
[4d2434a]334 }
335 }
336 }
337
338 // if array came with an initializer list: initialize each element
339 // may have more initializers than elements in the array - need to check at each index that
340 // we haven't exceeded size.
341 // may have fewer initializers than elements in the array - need to default construct
342 // remaining elements.
343 // To accomplish this, generate switch statement, consuming all of expander's elements
[b8524ca]344 Statement * InitImpl_old::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
[22bc276]345 if ( ! init ) return nullptr;
[ba3706f]346 CompoundStmt * block = new CompoundStmt();
[f9cebb5]347 build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
348 if ( block->get_kids().empty() ) {
349 delete block;
[22bc276]350 return nullptr;
[4d2434a]351 } else {
[22bc276]352 init = nullptr; // init was consumed in creating the list init
[f9cebb5]353 return block;
[4d2434a]354 }
[39f84a4]355 }
356
[b8524ca]357 Statement * ExprImpl_old::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
[22bc276]358 return nullptr;
[4d2434a]359 }
360
[b8524ca]361 Statement * InitExpander_old::buildListInit( UntypedExpr * dst ) {
[4d2434a]362 return expander->buildListInit( dst, indices );
363 }
364
[b8524ca]365class InitExpander_new::ExpanderImpl {
366public:
367 virtual ~ExpanderImpl() = default;
368 virtual std::vector< ast::ptr< ast::Expr > > next( IndexList & indices ) = 0;
[6f096d2]369 virtual ast::ptr< ast::Stmt > buildListInit(
[c1ed2ee]370 ast::UntypedExpr * callExpr, IndexList & indices ) = 0;
[b8524ca]371};
372
373namespace {
[c1ed2ee]374 template< typename Out >
[6f096d2]375 void buildCallExpr(
376 ast::UntypedExpr * callExpr, const ast::Expr * index, const ast::Expr * dimension,
[c1ed2ee]377 const ast::Init * init, Out & out
378 ) {
379 const CodeLocation & loc = init->location;
380
[6f096d2]381 auto cond = new ast::UntypedExpr{
[c1ed2ee]382 loc, new ast::NameExpr{ loc, "?<?" }, { index, dimension } };
[6f096d2]383
[c1ed2ee]384 std::vector< ast::ptr< ast::Expr > > args = makeInitList( init );
385 splice( callExpr->args, args );
386
387 out.emplace_back( new ast::IfStmt{ loc, cond, new ast::ExprStmt{ loc, callExpr } } );
388
[6f096d2]389 out.emplace_back( new ast::ExprStmt{
[c1ed2ee]390 loc, new ast::UntypedExpr{ loc, new ast::NameExpr{ loc, "++?" }, { index } } } );
391 }
392
393 template< typename Out >
394 void build(
[6f096d2]395 ast::UntypedExpr * callExpr, const InitExpander_new::IndexList & indices,
[c1ed2ee]396 const ast::Init * init, Out & out
397 ) {
398 if ( indices.empty() ) return;
399
400 unsigned idx = 0;
401
402 const ast::Expr * index = indices[idx++];
403 assert( idx != indices.size() );
404 const ast::Expr * dimension = indices[idx++];
405
406 if ( idx == indices.size() ) {
407 if ( auto listInit = dynamic_cast< const ast::ListInit * >( init ) ) {
408 for ( const ast::Init * init : *listInit ) {
[16ba4a6f]409 buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
[c1ed2ee]410 }
411 } else {
[16ba4a6f]412 buildCallExpr( shallowCopy(callExpr), index, dimension, init, out );
[c1ed2ee]413 }
414 } else {
415 const CodeLocation & loc = init->location;
416
417 unsigned long cond = 0;
418 auto listInit = dynamic_cast< const ast::ListInit * >( init );
419 if ( ! listInit ) { SemanticError( loc, "unbalanced list initializers" ); }
420
421 static UniqueName targetLabel( "L__autogen__" );
[6f096d2]422 ast::Label switchLabel{
[c1ed2ee]423 loc, targetLabel.newName(), { new ast::Attribute{ "unused" } } };
[6f096d2]424
[400b8be]425 std::vector< ast::ptr< ast::CaseClause > > branches;
[c1ed2ee]426 for ( const ast::Init * init : *listInit ) {
427 auto condition = ast::ConstantExpr::from_ulong( loc, cond );
428 ++cond;
429
430 std::vector< ast::ptr< ast::Stmt > > stmts;
431 build( callExpr, indices, init, stmts );
[6f096d2]432 stmts.emplace_back(
[c1ed2ee]433 new ast::BranchStmt{ loc, ast::BranchStmt::Break, switchLabel } );
[400b8be]434 branches.emplace_back( new ast::CaseClause{ loc, condition, std::move( stmts ) } );
[c1ed2ee]435 }
436 out.emplace_back( new ast::SwitchStmt{ loc, index, std::move( branches ) } );
437 out.emplace_back( new ast::NullStmt{ loc, { switchLabel } } );
438 }
439 }
440
[b8524ca]441 class InitImpl_new final : public InitExpander_new::ExpanderImpl {
442 ast::ptr< ast::Init > init;
443 public:
444 InitImpl_new( const ast::Init * i ) : init( i ) {}
445
446 std::vector< ast::ptr< ast::Expr > > next( InitExpander_new::IndexList & ) override {
447 return makeInitList( init );
448 }
[6f096d2]449
450 ast::ptr< ast::Stmt > buildListInit(
451 ast::UntypedExpr * callExpr, InitExpander_new::IndexList & indices
[b8524ca]452 ) override {
[6f096d2]453 // If array came with an initializer list, initialize each element. We may have more
454 // initializers than elements of the array; need to check at each index that we have
455 // not exceeded size. We may have fewer initializers than elements in the array; need
456 // to default-construct remaining elements. To accomplish this, generate switch
[c1ed2ee]457 // statement consuming all of expander's elements
458
459 if ( ! init ) return {};
460
461 std::list< ast::ptr< ast::Stmt > > stmts;
462 build( callExpr, indices, init, stmts );
463 if ( stmts.empty() ) {
464 return {};
465 } else {
466 auto block = new ast::CompoundStmt{ init->location, std::move( stmts ) };
467 init = nullptr; // consumed in creating the list init
468 return block;
469 }
[b8524ca]470 }
471 };
472
473 class ExprImpl_new final : public InitExpander_new::ExpanderImpl {
474 ast::ptr< ast::Expr > arg;
475 public:
476 ExprImpl_new( const ast::Expr * a ) : arg( a ) {}
477
[6f096d2]478 std::vector< ast::ptr< ast::Expr > > next(
479 InitExpander_new::IndexList & indices
[b8524ca]480 ) override {
[c1ed2ee]481 if ( ! arg ) return {};
482
483 const CodeLocation & loc = arg->location;
484 const ast::Expr * expr = arg;
485 for ( auto it = indices.rbegin(); it != indices.rend(); ++it ) {
486 // go through indices and layer on subscript exprs ?[?]
487 ++it;
[6f096d2]488 expr = new ast::UntypedExpr{
[c1ed2ee]489 loc, new ast::NameExpr{ loc, "?[?]" }, { expr, *it } };
490 }
491 return { expr };
[b8524ca]492 }
[6f096d2]493
494 ast::ptr< ast::Stmt > buildListInit(
495 ast::UntypedExpr *, InitExpander_new::IndexList &
496 ) override {
[b8524ca]497 return {};
498 }
499 };
500} // anonymous namespace
501
502InitExpander_new::InitExpander_new( const ast::Init * init )
503: expander( new InitImpl_new{ init } ), crnt(), indices() {}
504
505InitExpander_new::InitExpander_new( const ast::Expr * expr )
506: expander( new ExprImpl_new{ expr } ), crnt(), indices() {}
507
508std::vector< ast::ptr< ast::Expr > > InitExpander_new::operator* () { return crnt; }
509
510InitExpander_new & InitExpander_new::operator++ () {
511 crnt = expander->next( indices );
512 return *this;
513}
514
[6f096d2]515/// builds statement which has the same semantics as a C-style list initializer (for array
[b8524ca]516/// initializers) using callExpr as the base expression to perform initialization
[c1ed2ee]517ast::ptr< ast::Stmt > InitExpander_new::buildListInit( ast::UntypedExpr * callExpr ) {
[b8524ca]518 return expander->buildListInit( callExpr, indices );
519}
520
521void InitExpander_new::addArrayIndex( const ast::Expr * index, const ast::Expr * dimension ) {
522 indices.emplace_back( index );
523 indices.emplace_back( dimension );
524}
525
526void InitExpander_new::clearArrayIndices() { indices.clear(); }
527
528bool InitExpander_new::addReference() {
529 for ( ast::ptr< ast::Expr > & expr : crnt ) {
530 expr = new ast::AddressExpr{ expr };
531 }
532 return ! crnt.empty();
533}
534
[549c006]535 Type * getTypeofThis( FunctionType * ftype ) {
536 assertf( ftype, "getTypeofThis: nullptr ftype" );
537 ObjectDecl * thisParam = getParamThis( ftype );
[7fc7cdb]538 ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
539 return refType->base;
540 }
541
[3cc1111]542 const ast::Type * getTypeofThis( const ast::FunctionType * ftype ) {
543 assertf( ftype, "getTypeofThis: nullptr ftype" );
544 const std::vector<ast::ptr<ast::Type>> & params = ftype->params;
545 assertf( !params.empty(), "getTypeofThis: ftype with 0 parameters: %s",
546 toString( ftype ).c_str() );
547 const ast::ReferenceType * refType =
548 params.front().strict_as<ast::ReferenceType>();
549 return refType->base;
550 }
551
[549c006]552 ObjectDecl * getParamThis( FunctionType * ftype ) {
553 assertf( ftype, "getParamThis: nullptr ftype" );
[7fc7cdb]554 auto & params = ftype->parameters;
[549c006]555 assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
[7fc7cdb]556 return strict_dynamic_cast< ObjectDecl * >( params.front() );
557 }
558
[490fb92e]559 const ast::ObjectDecl * getParamThis(const ast::FunctionDecl * func) {
560 assertf( func, "getParamThis: nullptr ftype" );
561 auto & params = func->params;
562 assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( func ).c_str());
563 return params.front().strict_as<ast::ObjectDecl>();
564 }
565
[22bc276]566 bool tryConstruct( DeclarationWithType * dwt ) {
567 ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
568 if ( ! objDecl ) return false;
[df7a162]569 return (objDecl->get_init() == nullptr ||
[22bc276]570 ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
571 && ! objDecl->get_storageClasses().is_extern
[29bc63e]572 && isConstructable( objDecl->type );
573 }
574
575 bool isConstructable( Type * type ) {
576 return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
[64071c2]577 }
[2b46a13]578
[490fb92e]579 bool tryConstruct( const ast::DeclWithType * dwt ) {
580 auto objDecl = dynamic_cast< const ast::ObjectDecl * >( dwt );
581 if ( ! objDecl ) return false;
582 return (objDecl->init == nullptr ||
583 ( objDecl->init != nullptr && objDecl->init->maybeConstructed ))
584 && ! objDecl->storage.is_extern
585 && isConstructable( objDecl->type );
586 }
587
588 bool isConstructable( const ast::Type * type ) {
[720f2fe2]589 return ! dynamic_cast< const ast::VarArgsType * >( type ) && ! dynamic_cast< const ast::ReferenceType * >( type )
[490fb92e]590 && ! dynamic_cast< const ast::FunctionType * >( type ) && ! Tuples::isTtype( type );
591 }
592
[2d11663]593 struct CallFinder_old {
594 CallFinder_old( const std::list< std::string > & names ) : names( names ) {}
[4d2434a]595
[0a6aad4]596 void postvisit( ApplicationExpr * appExpr ) {
[4d2434a]597 handleCallExpr( appExpr );
598 }
599
[0a6aad4]600 void postvisit( UntypedExpr * untypedExpr ) {
[4d2434a]601 handleCallExpr( untypedExpr );
602 }
603
604 std::list< Expression * > * matches;
605 private:
606 const std::list< std::string > names;
607
608 template< typename CallExpr >
609 void handleCallExpr( CallExpr * expr ) {
610 std::string fname = getFunctionName( expr );
611 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
612 matches->push_back( expr );
[cad355a]613 }
[64071c2]614 }
[4d2434a]615 };
616
[2d11663]617 struct CallFinder_new final {
[490fb92e]618 std::vector< const ast::Expr * > matches;
[2d11663]619 const std::vector< std::string > names;
620
621 CallFinder_new( std::vector< std::string > && ns ) : matches(), names( std::move(ns) ) {}
622
623 void handleCallExpr( const ast::Expr * expr ) {
624 std::string fname = getFunctionName( expr );
625 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
626 matches.emplace_back( expr );
627 }
628 }
629
630 void postvisit( const ast::ApplicationExpr * expr ) { handleCallExpr( expr ); }
631 void postvisit( const ast::UntypedExpr * expr ) { handleCallExpr( expr ); }
632 };
633
[4d2434a]634 void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
[2d11663]635 static PassVisitor<CallFinder_old> finder( std::list< std::string >{ "?{}", "^?{}" } );
[0a6aad4]636 finder.pass.matches = &matches;
[4d2434a]637 maybeAccept( stmt, finder );
[64071c2]638 }
[4d2434a]639
[490fb92e]640 std::vector< const ast::Expr * > collectCtorDtorCalls( const ast::Stmt * stmt ) {
[2d11663]641 ast::Pass< CallFinder_new > finder{ std::vector< std::string >{ "?{}", "^?{}" } };
642 maybe_accept( stmt, finder );
[7ff3e522]643 return std::move( finder.core.matches );
[2d11663]644 }
645
[4d2434a]646 Expression * getCtorDtorCall( Statement * stmt ) {
647 std::list< Expression * > matches;
648 collectCtorDtorCalls( stmt, matches );
[20eacb7]649 assertf( matches.size() <= 1, "%zd constructor/destructors found in %s", matches.size(), toString( stmt ).c_str() );
[22bc276]650 return matches.size() == 1 ? matches.front() : nullptr;
[4d2434a]651 }
652
[aedfd91]653 namespace {
[599b386]654 DeclarationWithType * getCalledFunction( Expression * expr );
[d7aa12c]655 const ast::DeclWithType * getCalledFunction( const ast::Expr * expr );
[599b386]656
657 template<typename CallExpr>
658 DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
659 // (*f)(x) => should get "f"
660 std::string name = getFunctionName( expr );
661 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]662 assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
[599b386]663 return getCalledFunction( expr->get_args().front() );
664 }
665
[d7aa12c]666 template<typename CallExpr>
667 const ast::DeclWithType * handleDerefCalledFunction( const CallExpr * expr ) {
668 // (*f)(x) => should get "f"
669 std::string name = getFunctionName( expr );
670 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
671 assertf( ! expr->args.empty(), "Cannot get called function from dereference with no arguments" );
672 return getCalledFunction( expr->args.front() );
673 }
674
675
[ee1635c8]676 DeclarationWithType * getCalledFunction( Expression * expr ) {
677 assert( expr );
678 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
[6fc5c14]679 return varExpr->var;
[ee1635c8]680 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
[6fc5c14]681 return memberExpr->member;
[ee1635c8]682 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
[6fc5c14]683 return getCalledFunction( castExpr->arg );
[599b386]684 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
685 return handleDerefCalledFunction( untypedExpr );
686 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
687 return handleDerefCalledFunction( appExpr );
[f3b0a07]688 } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
[6fc5c14]689 return getCalledFunction( addrExpr->arg );
690 } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
691 return getCalledFunction( commaExpr->arg2 );
[ee1635c8]692 }
693 return nullptr;
[aedfd91]694 }
[d7aa12c]695
696 const ast::DeclWithType * getCalledFunction( const ast::Expr * expr ) {
697 assert( expr );
698 if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
699 return varExpr->var;
700 } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
701 return memberExpr->member;
702 } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
703 return getCalledFunction( castExpr->arg );
704 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( expr ) ) {
705 return handleDerefCalledFunction( untypedExpr );
706 } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * > ( expr ) ) {
707 return handleDerefCalledFunction( appExpr );
708 } else if ( const ast::AddressExpr * addrExpr = dynamic_cast< const ast::AddressExpr * >( expr ) ) {
709 return getCalledFunction( addrExpr->arg );
710 } else if ( const ast::CommaExpr * commaExpr = dynamic_cast< const ast::CommaExpr * >( expr ) ) {
711 return getCalledFunction( commaExpr->arg2 );
712 }
713 return nullptr;
714 }
[335d81f]715
716 DeclarationWithType * getFunctionCore( const Expression * expr ) {
717 if ( const auto * appExpr = dynamic_cast< const ApplicationExpr * >( expr ) ) {
718 return getCalledFunction( appExpr->function );
719 } else if ( const auto * untyped = dynamic_cast< const UntypedExpr * >( expr ) ) {
720 return getCalledFunction( untyped->function );
721 }
722 assertf( false, "getFunction with unknown expression: %s", toString( expr ).c_str() );
723 }
[aedfd91]724 }
[70f89d00]725
[b7b8674]726 DeclarationWithType * getFunction( Expression * expr ) {
[335d81f]727 return getFunctionCore( expr );
728 }
729
730 const DeclarationWithType * getFunction( const Expression * expr ) {
731 return getFunctionCore( expr );
[b7b8674]732 }
733
[d7aa12c]734 const ast::DeclWithType * getFunction( const ast::Expr * expr ) {
735 if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
736 return getCalledFunction( appExpr->func );
737 } else if ( const ast::UntypedExpr * untyped = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
738 return getCalledFunction( untyped->func );
739 }
740 assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
741 }
742
[aedfd91]743 ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
744 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
[22bc276]745 if ( ! appExpr ) return nullptr;
[ee1635c8]746 DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
[f3b0a07]747 assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
[64071c2]748 // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
749 // will call all member dtors, and some members may have a user defined dtor.
[22bc276]750 return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
[aedfd91]751 }
752
[2d11663]753 const ast::ApplicationExpr * isIntrinsicCallExpr( const ast::Expr * expr ) {
754 auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr );
755 if ( ! appExpr ) return nullptr;
756
757 const ast::DeclWithType * func = getCalledFunction( appExpr->func );
[6f096d2]758 assertf( func,
[2d11663]759 "getCalledFunction returned nullptr: %s", toString( appExpr->func ).c_str() );
[6f096d2]760
761 // check for Intrinsic only -- don't want to remove all overridable ctor/dtor because
762 // autogenerated ctor/dtor will call all member dtors, and some members may have a
[2d11663]763 // user-defined dtor
764 return func->linkage == ast::Linkage::Intrinsic ? appExpr : nullptr;
765 }
766
[a465caff]767 namespace {
768 template <typename Predicate>
769 bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
770 std::list< Expression * > callExprs;
771 collectCtorDtorCalls( stmt, callExprs );
772 // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
773 return std::all_of( callExprs.begin(), callExprs.end(), pred);
774 }
[2d11663]775
776 template <typename Predicate>
777 bool allofCtorDtor( const ast::Stmt * stmt, const Predicate & pred ) {
[490fb92e]778 std::vector< const ast::Expr * > callExprs = collectCtorDtorCalls( stmt );
[2d11663]779 return std::all_of( callExprs.begin(), callExprs.end(), pred );
780 }
[a465caff]781 }
782
[f9cebb5]783 bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
[a465caff]784 return allofCtorDtor( stmt, []( Expression * callExpr ){
[4d2434a]785 if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[f072892]786 FunctionType *funcType = GenPoly::getFunctionType( appExpr->function->result );
[4d2434a]787 assert( funcType );
788 return funcType->get_parameters().size() == 1;
789 }
790 return false;
[2d11663]791 });
792 }
793
794 bool isIntrinsicSingleArgCallStmt( const ast::Stmt * stmt ) {
795 return allofCtorDtor( stmt, []( const ast::Expr * callExpr ){
796 if ( const ast::ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
[6f096d2]797 const ast::FunctionType * funcType =
[2d11663]798 GenPoly::getFunctionType( appExpr->func->result );
799 assert( funcType );
800 return funcType->params.size() == 1;
801 }
802 return false;
[4d2434a]803 });
[64071c2]804 }
[f1b1e4c]805
[a465caff]806 bool isIntrinsicCallStmt( Statement * stmt ) {
807 return allofCtorDtor( stmt, []( Expression * callExpr ) {
808 return isIntrinsicCallExpr( callExpr );
809 });
810 }
811
[64071c2]812 namespace {
813 template<typename CallExpr>
814 Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
[a61ad31]815 if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
[64071c2]816 for ( Expression *& arg : callExpr->get_args() ) {
817 if ( pos == 0 ) return arg;
818 pos--;
819 }
820 assert( false );
821 }
[9b4f329]822
[b5fed34]823 template<typename CallExpr>
824 const ast::Expr * callArg( const CallExpr * call, unsigned int pos ) {
825 if( pos >= call->args.size() ) {
826 assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.",
827 pos, toString( call ).c_str() );
828 }
829 for ( const ast::Expr * arg : call->args ) {
830 if ( pos == 0 ) return arg;
831 --pos;
832 }
833 assert( false );
834 }
[64071c2]835 }
[f1b1e4c]836
[64071c2]837 Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
838 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
839 return callArg( appExpr, pos );
840 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
841 return callArg( untypedExpr, pos );
[f3b0a07]842 } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
843 std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
844 assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
[e3e16bc]845 ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
846 TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
[f3b0a07]847 assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
848 return getCallArg( tuple->get_exprs().front(), pos );
[62a05d1]849 } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
850 return getCallArg( copyCtor->callExpr, pos );
[64071c2]851 } else {
[f3b0a07]852 assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
[64071c2]853 }
854 }
[b5fed34]855
[9b4f329]856 const ast::Expr * getCallArg( const ast::Expr * call, unsigned pos ) {
[b5fed34]857 if ( auto app = dynamic_cast< const ast::ApplicationExpr * >( call ) ) {
858 return callArg( app, pos );
859 } else if ( auto untyped = dynamic_cast< const ast::UntypedExpr * >( call ) ) {
860 return callArg( untyped, pos );
861 } else if ( auto tupleAssn = dynamic_cast< const ast::TupleAssignExpr * >( call ) ) {
862 const std::list<ast::ptr<ast::Stmt>>& stmts = tupleAssn->stmtExpr->stmts->kids;
863 assertf( ! stmts.empty(), "TupleAssignExpr missing statements." );
864 auto stmt = strict_dynamic_cast< const ast::ExprStmt * >( stmts.back().get() );
865 auto tuple = strict_dynamic_cast< const ast::TupleExpr * >( stmt->expr.get() );
866 assertf( ! tuple->exprs.empty(), "TupleAssignExpr has empty tuple expr.");
867 return getCallArg( tuple->exprs.front(), pos );
868 } else if ( auto ctor = dynamic_cast< const ast::ImplicitCopyCtorExpr * >( call ) ) {
869 return getCallArg( ctor->callExpr, pos );
870 } else {
871 assertf( false, "Unexpected expression type passed to getCallArg: %s",
872 toString( call ).c_str() );
873 }
[9b4f329]874 }
[f1b1e4c]875
[64071c2]876 namespace {
[599b386]877 std::string funcName( Expression * func );
[d7aa12c]878 std::string funcName( const ast::Expr * func );
[599b386]879
880 template<typename CallExpr>
881 std::string handleDerefName( CallExpr * expr ) {
882 // (*f)(x) => should get name "f"
883 std::string name = getFunctionName( expr );
884 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
[b128d3e]885 assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
[599b386]886 return funcName( expr->get_args().front() );
887 }
888
[d7aa12c]889 template<typename CallExpr>
890 std::string handleDerefName( const CallExpr * expr ) {
891 // (*f)(x) => should get name "f"
892 std::string name = getFunctionName( expr );
893 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
894 assertf( ! expr->args.empty(), "Cannot get function name from dereference with no arguments" );
895 return funcName( expr->args.front() );
896 }
897
[c738ca4]898 std::string funcName( Expression * func ) {
[64071c2]899 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
900 return nameExpr->get_name();
901 } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
902 return varExpr->get_var()->get_name();
[c738ca4]903 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
904 return funcName( castExpr->get_arg() );
[ee1635c8]905 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
906 return memberExpr->get_member()->get_name();
[96a10cdd]907 } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
[fd782b2]908 return funcName( memberExpr->get_member() );
[599b386]909 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
910 return handleDerefName( untypedExpr );
911 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
912 return handleDerefName( appExpr );
[19a9822]913 } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
914 return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
[64071c2]915 } else {
[19a9822]916 assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
[64071c2]917 }
918 }
[d7aa12c]919
920 std::string funcName( const ast::Expr * func ) {
921 if ( const ast::NameExpr * nameExpr = dynamic_cast< const ast::NameExpr * >( func ) ) {
922 return nameExpr->name;
923 } else if ( const ast::VariableExpr * varExpr = dynamic_cast< const ast::VariableExpr * >( func ) ) {
924 return varExpr->var->name;
925 } else if ( const ast::CastExpr * castExpr = dynamic_cast< const ast::CastExpr * >( func ) ) {
926 return funcName( castExpr->arg );
927 } else if ( const ast::MemberExpr * memberExpr = dynamic_cast< const ast::MemberExpr * >( func ) ) {
928 return memberExpr->member->name;
929 } else if ( const ast::UntypedMemberExpr * memberExpr = dynamic_cast< const ast::UntypedMemberExpr * > ( func ) ) {
930 return funcName( memberExpr->member );
931 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * >( func ) ) {
932 return handleDerefName( untypedExpr );
933 } else if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( func ) ) {
934 return handleDerefName( appExpr );
935 } else if ( const ast::ConstructorExpr * ctorExpr = dynamic_cast< const ast::ConstructorExpr * >( func ) ) {
936 return funcName( getCallArg( ctorExpr->callExpr, 0 ) );
937 } else {
938 assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
939 }
940 }
[64071c2]941 }
[70f89d00]942
[64071c2]943 std::string getFunctionName( Expression * expr ) {
[599b386]944 // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
945 // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
946 // can't possibly do anything reasonable.
[64071c2]947 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
[c738ca4]948 return funcName( appExpr->get_function() );
[64071c2]949 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
[c738ca4]950 return funcName( untypedExpr->get_function() );
[64071c2]951 } else {
[c738ca4]952 std::cerr << expr << std::endl;
[d1969a6]953 assertf( false, "Unexpected expression type passed to getFunctionName" );
[64071c2]954 }
955 }
[10a7775]956
[d7aa12c]957 std::string getFunctionName( const ast::Expr * expr ) {
958 // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
959 // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
960 // can't possibly do anything reasonable.
961 if ( const ast::ApplicationExpr * appExpr = dynamic_cast< const ast::ApplicationExpr * >( expr ) ) {
962 return funcName( appExpr->func );
963 } else if ( const ast::UntypedExpr * untypedExpr = dynamic_cast< const ast::UntypedExpr * > ( expr ) ) {
964 return funcName( untypedExpr->func );
965 } else {
966 std::cerr << expr << std::endl;
967 assertf( false, "Unexpected expression type passed to getFunctionName" );
968 }
969 }
970
[64071c2]971 Type * getPointerBase( Type * type ) {
972 if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
973 return ptrType->get_base();
974 } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
975 return arrayType->get_base();
[ce8c12f]976 } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
977 return refType->get_base();
[64071c2]978 } else {
[22bc276]979 return nullptr;
[64071c2]980 }
981 }
[9e1d485]982 const ast::Type* getPointerBase( const ast::Type* t ) {
[b5fed34]983 if ( const auto * p = dynamic_cast< const ast::PointerType * >( t ) ) {
984 return p->base;
985 } else if ( const auto * a = dynamic_cast< const ast::ArrayType * >( t ) ) {
986 return a->base;
987 } else if ( const auto * r = dynamic_cast< const ast::ReferenceType * >( t ) ) {
988 return r->base;
989 } else return nullptr;
[9e1d485]990 }
[10a7775]991
[64071c2]992 Type * isPointerType( Type * type ) {
993 if ( getPointerBase( type ) ) return type;
[22bc276]994 else return nullptr;
[64071c2]995 }
[40e636a]996
[f5c3b6c]997 ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
998 static FunctionDecl * assign = nullptr;
999 if ( ! assign ) {
1000 // temporary? Generate a fake assignment operator to represent bitwise assignments.
1001 // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
1002 TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
1003 assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
1004 }
1005 if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
[5002738]1006 for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
1007 dst = new AddressExpr( dst );
1008 }
[f5c3b6c]1009 } else {
1010 dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
1011 }
1012 if ( dynamic_cast< ReferenceType * >( src->result ) ) {
[5002738]1013 for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1014 src = new AddressExpr( src );
1015 }
[ba89e9b7]1016 // src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
[f5c3b6c]1017 }
1018 return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
1019 }
1020
[490fb92e]1021 // looks like some other such codegen uses UntypedExpr and does not create fake function. should revisit afterwards
1022 // following passes may accidentally resolve this expression if returned as untyped...
1023 ast::Expr * createBitwiseAssignment (const ast::Expr * dst, const ast::Expr * src) {
1024 static ast::ptr<ast::FunctionDecl> assign = nullptr;
1025 if (!assign) {
1026 auto td = new ast::TypeDecl({}, "T", {}, nullptr, ast::TypeDecl::Dtype, true);
[720f2fe2]1027 assign = new ast::FunctionDecl({}, "?=?", {},
[490fb92e]1028 { new ast::ObjectDecl({}, "_dst", new ast::ReferenceType(new ast::TypeInstType("T", td))),
1029 new ast::ObjectDecl({}, "_src", new ast::TypeInstType("T", td))},
1030 { new ast::ObjectDecl({}, "_ret", new ast::TypeInstType("T", td))}, nullptr, {}, ast::Linkage::Intrinsic);
1031 }
1032 if (dst->result.as<ast::ReferenceType>()) {
1033 for (int depth = dst->result->referenceDepth(); depth > 0; depth--) {
1034 dst = new ast::AddressExpr(dst);
1035 }
1036 }
1037 else {
1038 dst = new ast::CastExpr(dst, new ast::ReferenceType(dst->result, {}));
1039 }
1040 if (src->result.as<ast::ReferenceType>()) {
1041 for (int depth = src->result->referenceDepth(); depth > 0; depth--) {
1042 src = new ast::AddressExpr(src);
1043 }
1044 }
1045 return new ast::ApplicationExpr(dst->location, ast::VariableExpr::functionPointer(dst->location, assign), {dst, src});
1046 }
1047
[c5f3c68]1048 struct ConstExprChecker : public WithShortCircuiting {
1049 // most expressions are not const expr
1050 void previsit( Expression * ) { isConstExpr = false; visit_children = false; }
[40e636a]1051
[c5f3c68]1052 void previsit( AddressExpr *addressExpr ) {
1053 visit_children = false;
[65dc863]1054
[1ba88a0]1055 // address of a variable or member expression is constexpr
1056 Expression * arg = addressExpr->get_arg();
1057 if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
1058 }
[c5f3c68]1059
1060 // these expressions may be const expr, depending on their children
1061 void previsit( SizeofExpr * ) {}
1062 void previsit( AlignofExpr * ) {}
1063 void previsit( UntypedOffsetofExpr * ) {}
1064 void previsit( OffsetofExpr * ) {}
1065 void previsit( OffsetPackExpr * ) {}
1066 void previsit( CommaExpr * ) {}
1067 void previsit( LogicalExpr * ) {}
1068 void previsit( ConditionalExpr * ) {}
1069 void previsit( CastExpr * ) {}
1070 void previsit( ConstantExpr * ) {}
1071
[caab997]1072 void previsit( VariableExpr * varExpr ) {
1073 visit_children = false;
1074
1075 if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( varExpr->result ) ) {
1076 long long int value;
1077 if ( inst->baseEnum->valueOf( varExpr->var, value ) ) {
1078 // enumerators are const expr
1079 return;
1080 }
1081 }
1082 isConstExpr = false;
1083 }
1084
[c5f3c68]1085 bool isConstExpr = true;
[40e636a]1086 };
1087
[16ba4a6f]1088 struct ConstExprChecker_new : public ast::WithShortCircuiting {
1089 // most expressions are not const expr
1090 void previsit( const ast::Expr * ) { result = false; visit_children = false; }
1091
1092 void previsit( const ast::AddressExpr *addressExpr ) {
1093 visit_children = false;
1094 const ast::Expr * arg = addressExpr->arg;
1095
1096 // address of a variable or member expression is constexpr
[720f2fe2]1097 if ( ! dynamic_cast< const ast::NameExpr * >( arg )
1098 && ! dynamic_cast< const ast::VariableExpr * >( arg )
1099 && ! dynamic_cast< const ast::MemberExpr * >( arg )
[16ba4a6f]1100 && ! dynamic_cast< const ast::UntypedMemberExpr * >( arg ) ) result = false;
1101 }
1102
1103 // these expressions may be const expr, depending on their children
1104 void previsit( const ast::SizeofExpr * ) {}
1105 void previsit( const ast::AlignofExpr * ) {}
1106 void previsit( const ast::UntypedOffsetofExpr * ) {}
1107 void previsit( const ast::OffsetofExpr * ) {}
1108 void previsit( const ast::OffsetPackExpr * ) {}
1109 void previsit( const ast::CommaExpr * ) {}
1110 void previsit( const ast::LogicalExpr * ) {}
1111 void previsit( const ast::ConditionalExpr * ) {}
1112 void previsit( const ast::CastExpr * ) {}
1113 void previsit( const ast::ConstantExpr * ) {}
1114
1115 void previsit( const ast::VariableExpr * varExpr ) {
1116 visit_children = false;
1117
1118 if ( auto inst = varExpr->result.as<ast::EnumInstType>() ) {
1119 long long int value;
1120 if ( inst->base->valueOf( varExpr->var, value ) ) {
1121 // enumerators are const expr
1122 return;
1123 }
1124 }
1125 result = false;
1126 }
1127
1128 bool result = true;
1129 };
1130
[40e636a]1131 bool isConstExpr( Expression * expr ) {
1132 if ( expr ) {
[c5f3c68]1133 PassVisitor<ConstExprChecker> checker;
[40e636a]1134 expr->accept( checker );
[c5f3c68]1135 return checker.pass.isConstExpr;
[40e636a]1136 }
1137 return true;
1138 }
1139
1140 bool isConstExpr( Initializer * init ) {
1141 if ( init ) {
[c5f3c68]1142 PassVisitor<ConstExprChecker> checker;
[40e636a]1143 init->accept( checker );
[c5f3c68]1144 return checker.pass.isConstExpr;
[40e636a]1145 } // if
1146 // for all intents and purposes, no initializer means const expr
1147 return true;
1148 }
1149
[16ba4a6f]1150 bool isConstExpr( const ast::Expr * expr ) {
1151 if ( expr ) {
1152 ast::Pass<ConstExprChecker_new> checker;
1153 expr->accept( checker );
1154 return checker.core.result;
1155 }
1156 return true;
1157 }
1158
1159 bool isConstExpr( const ast::Init * init ) {
1160 if ( init ) {
1161 ast::Pass<ConstExprChecker_new> checker;
1162 init->accept( checker );
1163 return checker.core.result;
1164 } // if
1165 // for all intents and purposes, no initializer means const expr
1166 return true;
1167 }
1168
[79970ed]1169 bool isConstructor( const std::string & str ) { return str == "?{}"; }
1170 bool isDestructor( const std::string & str ) { return str == "^?{}"; }
[ee1635c8]1171 bool isAssignment( const std::string & str ) { return str == "?=?"; }
[79970ed]1172 bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
[ee1635c8]1173 bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
[4d4882a]1174
[6f096d2]1175 const FunctionDecl * isCopyFunction( const Declaration * decl, const std::string & fname ) {
1176 const FunctionDecl * function = dynamic_cast< const FunctionDecl * >( decl );
[0a267c1]1177 if ( ! function ) return nullptr;
1178 if ( function->name != fname ) return nullptr;
1179 FunctionType * ftype = function->type;
1180 if ( ftype->parameters.size() != 2 ) return nullptr;
[4d4882a]1181
[ce8c12f]1182 Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
[0a267c1]1183 Type * t2 = ftype->parameters.back()->get_type();
[ce8c12f]1184 assert( t1 );
[4d4882a]1185
[ce8c12f]1186 if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
[4d4882a]1187 return function;
1188 } else {
[ee1635c8]1189 return nullptr;
[4d4882a]1190 }
1191 }
[ee1635c8]1192
[00a8e19]1193bool isAssignment( const ast::FunctionDecl * decl ) {
1194 return isAssignment( decl->name ) && isCopyFunction( decl );
1195}
[d76c588]1196
[00a8e19]1197bool isDestructor( const ast::FunctionDecl * decl ) {
1198 return isDestructor( decl->name );
1199}
[6f096d2]1200
[00a8e19]1201bool isDefaultConstructor( const ast::FunctionDecl * decl ) {
1202 return isConstructor( decl->name ) && 1 == decl->params.size();
1203}
1204
1205bool isCopyConstructor( const ast::FunctionDecl * decl ) {
1206 return isConstructor( decl->name ) && 2 == decl->params.size();
1207}
1208
1209bool isCopyFunction( const ast::FunctionDecl * decl ) {
1210 const ast::FunctionType * ftype = decl->type;
1211 if ( ftype->params.size() != 2 ) return false;
1212
1213 const ast::Type * t1 = getPointerBase( ftype->params.front() );
1214 if ( ! t1 ) return false;
1215 const ast::Type * t2 = ftype->params.back();
1216
1217 return ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, ast::SymbolTable{} );
1218}
[d76c588]1219
[6f096d2]1220 const FunctionDecl * isAssignment( const Declaration * decl ) {
[207c7e1d]1221 return isCopyFunction( decl, "?=?" );
1222 }
[6f096d2]1223 const FunctionDecl * isDestructor( const Declaration * decl ) {
1224 if ( isDestructor( decl->name ) ) {
1225 return dynamic_cast< const FunctionDecl * >( decl );
[207c7e1d]1226 }
1227 return nullptr;
1228 }
[6f096d2]1229 const FunctionDecl * isDefaultConstructor( const Declaration * decl ) {
[0a267c1]1230 if ( isConstructor( decl->name ) ) {
[6f096d2]1231 if ( const FunctionDecl * func = dynamic_cast< const FunctionDecl * >( decl ) ) {
[0a267c1]1232 if ( func->type->parameters.size() == 1 ) {
[207c7e1d]1233 return func;
1234 }
1235 }
1236 }
1237 return nullptr;
1238 }
[6f096d2]1239 const FunctionDecl * isCopyConstructor( const Declaration * decl ) {
[ee1635c8]1240 return isCopyFunction( decl, "?{}" );
1241 }
[f1791a4]1242
[720f2fe2]1243 #if defined( __x86_64 ) || defined( __i386 ) // assembler comment to prevent assembler warning message
1244 #define ASM_COMMENT "#"
1245 #else // defined( __ARM_ARCH )
1246 #define ASM_COMMENT "//"
1247 #endif
1248 static const char * const data_section = ".data" ASM_COMMENT;
1249 static const char * const tlsd_section = ".tdata" ASM_COMMENT;
1250 void addDataSectionAttribute( ObjectDecl * objDecl ) {
1251 const bool is_tls = objDecl->get_storageClasses().is_threadlocal;
1252 const char * section = is_tls ? tlsd_section : data_section;
[aff7e86]1253 objDecl->attributes.push_back(new Attribute("section", {
[720f2fe2]1254 new ConstantExpr( Constant::from_string( section ) )
1255 }));
[f1791a4]1256 }
1257
[7d651a66]1258 void addDataSectionAttribute( ast::ObjectDecl * objDecl ) {
[720f2fe2]1259 const bool is_tls = objDecl->storage.is_threadlocal;
1260 const char * section = is_tls ? tlsd_section : data_section;
[aff7e86]1261 objDecl->attributes.push_back(new ast::Attribute("section", {
[720f2fe2]1262 ast::ConstantExpr::from_string(objDecl->location, section)
1263 }));
[7d651a66]1264 }
1265
[2b46a13]1266}
Note: See TracBrowser for help on using the repository browser.