source: src/InitTweak/InitTweak.cc@ 49ae2bc

Last change on this file since 49ae2bc was 3c714ad, checked in by Andrew Beach <ajbeach@…>, 2 years ago

I don't actually know if this fixes anything, but the old version was definitely not doing anything and this is should have the same behaviour as the old one, and run just a bit faster.

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