source: src/InitTweak/InitTweak.cc@ 9e0a360

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 9e0a360 was c1ed2ee, checked in by Aaron Moss <a3moss@…>, 6 years ago

Continued resolver porting

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