source: src/InitTweak/InitTweak.cc@ 1fbeebd

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 1fbeebd was 1fbeebd, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert LabelFixer to PassVisitor

  • Property mode set to 100644
File size: 25.1 KB
Line 
1#include <algorithm> // for find, all_of
2#include <cassert> // for assertf, assert, strict_dynamic_cast
3#include <iostream> // for ostream, cerr, endl
4#include <iterator> // for back_insert_iterator, back_inserter
5#include <memory> // for __shared_ptr
6
7#include "Common/PassVisitor.h"
8#include "Common/SemanticError.h" // for SemanticError
9#include "Common/UniqueName.h" // for UniqueName
10#include "Common/utility.h" // for toString, deleteAll, maybeClone
11#include "GenPoly/GenPoly.h" // for getFunctionType
12#include "InitTweak.h"
13#include "Parser/LinkageSpec.h" // for Spec, isBuiltin, Intrinsic
14#include "ResolvExpr/typeops.h" // for typesCompatibleIgnoreQualifiers
15#include "SymTab/Autogen.h"
16#include "SymTab/Indexer.h" // for Indexer
17#include "SynTree/Attribute.h" // for Attribute
18#include "SynTree/Constant.h" // for Constant
19#include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType
20#include "SynTree/Expression.h" // for Expression, UntypedExpr, Applicati...
21#include "SynTree/Initializer.h" // for Initializer, ListInit, Designation
22#include "SynTree/Label.h" // for Label
23#include "SynTree/Statement.h" // for CompoundStmt, ExprStmt, BranchStmt
24#include "SynTree/Type.h" // for FunctionType, ArrayType, PointerType
25#include "SynTree/Visitor.h" // for Visitor, maybeAccept
26#include "Tuples/Tuples.h" // for Tuples::isTtype
27
28class UntypedValofExpr;
29
30namespace InitTweak {
31 namespace {
32 struct HasDesignations : public WithShortCircuiting {
33 bool hasDesignations = false;
34
35 void previsit( BaseSyntaxNode * ) {
36 // short circuit if we already know there are designations
37 if ( hasDesignations ) visit_children = false;
38 }
39
40 void previsit( Designation * des ) {
41 // short circuit if we already know there are designations
42 if ( hasDesignations ) visit_children = false;
43 else if ( ! des->get_designators().empty() ) {
44 hasDesignations = true;
45 visit_children = false;
46 }
47 }
48 };
49
50 class InitDepthChecker : public Visitor {
51 public:
52 bool depthOkay = true;
53 Type * type;
54 int curDepth = 0, maxDepth = 0;
55 InitDepthChecker( Type * type ) : type( type ) {
56 Type * t = type;
57 while ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
58 maxDepth++;
59 t = at->get_base();
60 }
61 maxDepth++;
62 }
63 virtual void visit( ListInit * listInit ) {
64 curDepth++;
65 if ( curDepth > maxDepth ) depthOkay = false;
66 Visitor::visit( listInit );
67 curDepth--;
68 }
69 };
70
71 class InitFlattener : public Visitor {
72 public:
73 virtual void visit( SingleInit * singleInit );
74 virtual void visit( ListInit * listInit );
75 std::list< Expression * > argList;
76 };
77
78 void InitFlattener::visit( SingleInit * singleInit ) {
79 argList.push_back( singleInit->get_value()->clone() );
80 }
81
82 void InitFlattener::visit( ListInit * listInit ) {
83 // flatten nested list inits
84 std::list<Initializer*>::iterator it = listInit->begin();
85 for ( ; it != listInit->end(); ++it ) {
86 (*it)->accept( *this );
87 }
88 }
89 }
90
91 std::list< Expression * > makeInitList( Initializer * init ) {
92 InitFlattener flattener;
93 maybeAccept( init, flattener );
94 return flattener.argList;
95 }
96
97 bool isDesignated( Initializer * init ) {
98 PassVisitor<HasDesignations> finder;
99 maybeAccept( init, finder );
100 return finder.pass.hasDesignations;
101 }
102
103 bool checkInitDepth( ObjectDecl * objDecl ) {
104 InitDepthChecker checker( objDecl->get_type() );
105 maybeAccept( objDecl->get_init(), checker );
106 return checker.depthOkay;
107 }
108
109 class InitExpander::ExpanderImpl {
110 public:
111 virtual ~ExpanderImpl() = default;
112 virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
113 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
114 };
115
116 class InitImpl : public InitExpander::ExpanderImpl {
117 public:
118 InitImpl( Initializer * init ) : init( init ) {}
119 virtual ~InitImpl() = default;
120
121 virtual std::list< Expression * > next( __attribute((unused)) std::list< Expression * > & indices ) {
122 // this is wrong, but just a placeholder for now
123 // if ( ! flattened ) flatten( indices );
124 // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
125 return makeInitList( init );
126 }
127
128 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
129 private:
130 Initializer * init;
131 };
132
133 class ExprImpl : public InitExpander::ExpanderImpl {
134 public:
135 ExprImpl( Expression * expr ) : arg( expr ) {}
136 virtual ~ExprImpl() { delete arg; }
137
138 virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
139 std::list< Expression * > ret;
140 Expression * expr = maybeClone( arg );
141 if ( expr ) {
142 for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
143 // go through indices and layer on subscript exprs ?[?]
144 ++it;
145 UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
146 subscriptExpr->get_args().push_back( expr );
147 subscriptExpr->get_args().push_back( (*it)->clone() );
148 expr = subscriptExpr;
149 }
150 ret.push_back( expr );
151 }
152 return ret;
153 }
154
155 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
156 private:
157 Expression * arg;
158 };
159
160 InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
161
162 InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
163
164 std::list< Expression * > InitExpander::operator*() {
165 return cur;
166 }
167
168 InitExpander & InitExpander::operator++() {
169 cur = expander->next( indices );
170 return *this;
171 }
172
173 // use array indices list to build switch statement
174 void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
175 indices.push_back( index );
176 indices.push_back( dimension );
177 }
178
179 void InitExpander::clearArrayIndices() {
180 deleteAll( indices );
181 indices.clear();
182 }
183
184 bool InitExpander::addReference() {
185 bool added = false;
186 for ( Expression *& expr : cur ) {
187 expr = new AddressExpr( expr );
188 added = true;
189 }
190 return added;
191 }
192
193 namespace {
194 /// given index i, dimension d, initializer init, and callExpr f, generates
195 /// if (i < d) f(..., init)
196 /// ++i;
197 /// so that only elements within the range of the array are constructed
198 template< typename OutIterator >
199 void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
200 UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
201 cond->get_args().push_back( index->clone() );
202 cond->get_args().push_back( dimension->clone() );
203
204 std::list< Expression * > args = makeInitList( init );
205 callExpr->get_args().splice( callExpr->get_args().end(), args );
206
207 *out++ = new IfStmt( cond, new ExprStmt( callExpr ), nullptr );
208
209 UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
210 increment->get_args().push_back( index->clone() );
211 *out++ = new ExprStmt( increment );
212 }
213
214 template< typename OutIterator >
215 void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
216 if ( idx == idxEnd ) return;
217 Expression * index = *idx++;
218 assert( idx != idxEnd );
219 Expression * dimension = *idx++;
220
221 // xxx - may want to eventually issue a warning here if we can detect
222 // that the number of elements exceeds to dimension of the array
223 if ( idx == idxEnd ) {
224 if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
225 for ( Initializer * init : *listInit ) {
226 buildCallExpr( callExpr->clone(), index, dimension, init, out );
227 }
228 } else {
229 buildCallExpr( callExpr->clone(), index, dimension, init, out );
230 }
231 } else {
232 std::list< Statement * > branches;
233
234 unsigned long cond = 0;
235 ListInit * listInit = dynamic_cast< ListInit * >( init );
236 if ( ! listInit ) {
237 // xxx - this shouldn't be an error, but need a way to
238 // terminate without creating output, so should catch this error
239 throw SemanticError( "unbalanced list initializers" );
240 }
241
242 static UniqueName targetLabel( "L__autogen__" );
243 Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
244 for ( Initializer * init : *listInit ) {
245 Expression * condition;
246 // check for designations
247 // if ( init-> ) {
248 condition = new ConstantExpr( Constant::from_ulong( cond ) );
249 ++cond;
250 // } else {
251 // condition = // ... take designation
252 // cond = // ... take designation+1
253 // }
254 std::list< Statement * > stmts;
255 build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
256 stmts.push_back( new BranchStmt( switchLabel, BranchStmt::Break ) );
257 CaseStmt * caseStmt = new CaseStmt( condition, stmts );
258 branches.push_back( caseStmt );
259 }
260 *out++ = new SwitchStmt( index->clone(), branches );
261 *out++ = new NullStmt( { switchLabel } );
262 }
263 }
264 }
265
266 // if array came with an initializer list: initialize each element
267 // may have more initializers than elements in the array - need to check at each index that
268 // we haven't exceeded size.
269 // may have fewer initializers than elements in the array - need to default construct
270 // remaining elements.
271 // To accomplish this, generate switch statement, consuming all of expander's elements
272 Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
273 if ( ! init ) return nullptr;
274 CompoundStmt * block = new CompoundStmt();
275 build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
276 if ( block->get_kids().empty() ) {
277 delete block;
278 return nullptr;
279 } else {
280 init = nullptr; // init was consumed in creating the list init
281 return block;
282 }
283 }
284
285 Statement * ExprImpl::buildListInit( UntypedExpr *, std::list< Expression * > & ) {
286 return nullptr;
287 }
288
289 Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
290 return expander->buildListInit( dst, indices );
291 }
292
293 Type * getTypeofThis( FunctionType * ftype ) {
294 assertf( ftype, "getTypeofThis: nullptr ftype" );
295 ObjectDecl * thisParam = getParamThis( ftype );
296 ReferenceType * refType = strict_dynamic_cast< ReferenceType * >( thisParam->type );
297 return refType->base;
298 }
299
300 ObjectDecl * getParamThis( FunctionType * ftype ) {
301 assertf( ftype, "getParamThis: nullptr ftype" );
302 auto & params = ftype->parameters;
303 assertf( ! params.empty(), "getParamThis: ftype with 0 parameters: %s", toString( ftype ).c_str() );
304 return strict_dynamic_cast< ObjectDecl * >( params.front() );
305 }
306
307 bool tryConstruct( DeclarationWithType * dwt ) {
308 ObjectDecl * objDecl = dynamic_cast< ObjectDecl * >( dwt );
309 if ( ! objDecl ) return false;
310 return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
311 (objDecl->get_init() == nullptr ||
312 ( objDecl->get_init() != nullptr && objDecl->get_init()->get_maybeConstructed() ))
313 && ! objDecl->get_storageClasses().is_extern
314 && isConstructable( objDecl->type );
315 }
316
317 bool isConstructable( Type * type ) {
318 return ! dynamic_cast< VarArgsType * >( type ) && ! dynamic_cast< ReferenceType * >( type ) && ! dynamic_cast< FunctionType * >( type ) && ! Tuples::isTtype( type );
319 }
320
321 class CallFinder : public Visitor {
322 public:
323 typedef Visitor Parent;
324 CallFinder( const std::list< std::string > & names ) : names( names ) {}
325
326 virtual void visit( ApplicationExpr * appExpr ) {
327 handleCallExpr( appExpr );
328 }
329
330 virtual void visit( UntypedExpr * untypedExpr ) {
331 handleCallExpr( untypedExpr );
332 }
333
334 std::list< Expression * > * matches;
335 private:
336 const std::list< std::string > names;
337
338 template< typename CallExpr >
339 void handleCallExpr( CallExpr * expr ) {
340 Parent::visit( expr );
341 std::string fname = getFunctionName( expr );
342 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
343 matches->push_back( expr );
344 }
345 }
346 };
347
348 void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
349 static CallFinder finder( std::list< std::string >{ "?{}", "^?{}" } );
350 finder.matches = &matches;
351 maybeAccept( stmt, finder );
352 }
353
354 Expression * getCtorDtorCall( Statement * stmt ) {
355 std::list< Expression * > matches;
356 collectCtorDtorCalls( stmt, matches );
357 assert( matches.size() <= 1 );
358 return matches.size() == 1 ? matches.front() : nullptr;
359 }
360
361 namespace {
362 DeclarationWithType * getCalledFunction( Expression * expr );
363
364 template<typename CallExpr>
365 DeclarationWithType * handleDerefCalledFunction( CallExpr * expr ) {
366 // (*f)(x) => should get "f"
367 std::string name = getFunctionName( expr );
368 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
369 assertf( ! expr->get_args().empty(), "Cannot get called function from dereference with no arguments" );
370 return getCalledFunction( expr->get_args().front() );
371 }
372
373 DeclarationWithType * getCalledFunction( Expression * expr ) {
374 assert( expr );
375 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
376 return varExpr->var;
377 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
378 return memberExpr->member;
379 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
380 return getCalledFunction( castExpr->arg );
381 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( expr ) ) {
382 return handleDerefCalledFunction( untypedExpr );
383 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * > ( expr ) ) {
384 return handleDerefCalledFunction( appExpr );
385 } else if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( expr ) ) {
386 return getCalledFunction( addrExpr->arg );
387 } else if ( CommaExpr * commaExpr = dynamic_cast< CommaExpr * >( expr ) ) {
388 return getCalledFunction( commaExpr->arg2 );
389 }
390 return nullptr;
391 }
392 }
393
394 DeclarationWithType * getFunction( Expression * expr ) {
395 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
396 return getCalledFunction( appExpr->get_function() );
397 } else if ( UntypedExpr * untyped = dynamic_cast< UntypedExpr * > ( expr ) ) {
398 return getCalledFunction( untyped->get_function() );
399 }
400 assertf( false, "getFunction received unknown expression: %s", toString( expr ).c_str() );
401 }
402
403 ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
404 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
405 if ( ! appExpr ) return nullptr;
406 DeclarationWithType * function = getCalledFunction( appExpr->get_function() );
407 assertf( function, "getCalledFunction returned nullptr: %s", toString( appExpr->get_function() ).c_str() );
408 // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
409 // will call all member dtors, and some members may have a user defined dtor.
410 return function->get_linkage() == LinkageSpec::Intrinsic ? appExpr : nullptr;
411 }
412
413 namespace {
414 template <typename Predicate>
415 bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
416 std::list< Expression * > callExprs;
417 collectCtorDtorCalls( stmt, callExprs );
418 // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
419 return std::all_of( callExprs.begin(), callExprs.end(), pred);
420 }
421 }
422
423 bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
424 return allofCtorDtor( stmt, []( Expression * callExpr ){
425 if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
426 FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_result() );
427 assert( funcType );
428 return funcType->get_parameters().size() == 1;
429 }
430 return false;
431 });
432 }
433
434 bool isIntrinsicCallStmt( Statement * stmt ) {
435 return allofCtorDtor( stmt, []( Expression * callExpr ) {
436 return isIntrinsicCallExpr( callExpr );
437 });
438 }
439
440 namespace {
441 template<typename CallExpr>
442 Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
443 if ( pos >= callExpr->get_args().size() ) assertf( false, "getCallArg for argument that doesn't exist: (%u); %s.", pos, toString( callExpr ).c_str() );
444 for ( Expression *& arg : callExpr->get_args() ) {
445 if ( pos == 0 ) return arg;
446 pos--;
447 }
448 assert( false );
449 }
450 }
451
452 Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
453 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
454 return callArg( appExpr, pos );
455 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
456 return callArg( untypedExpr, pos );
457 } else if ( TupleAssignExpr * tupleExpr = dynamic_cast< TupleAssignExpr * > ( callExpr ) ) {
458 std::list< Statement * > & stmts = tupleExpr->get_stmtExpr()->get_statements()->get_kids();
459 assertf( ! stmts.empty(), "TupleAssignExpr somehow has no statements." );
460 ExprStmt * stmt = strict_dynamic_cast< ExprStmt * >( stmts.back() );
461 TupleExpr * tuple = strict_dynamic_cast< TupleExpr * >( stmt->get_expr() );
462 assertf( ! tuple->get_exprs().empty(), "TupleAssignExpr somehow has empty tuple expr." );
463 return getCallArg( tuple->get_exprs().front(), pos );
464 } else if ( ImplicitCopyCtorExpr * copyCtor = dynamic_cast< ImplicitCopyCtorExpr * >( callExpr ) ) {
465 return getCallArg( copyCtor->callExpr, pos );
466 } else {
467 assertf( false, "Unexpected expression type passed to getCallArg: %s", toString( callExpr ).c_str() );
468 }
469 }
470
471 namespace {
472 std::string funcName( Expression * func );
473
474 template<typename CallExpr>
475 std::string handleDerefName( CallExpr * expr ) {
476 // (*f)(x) => should get name "f"
477 std::string name = getFunctionName( expr );
478 assertf( name == "*?", "Unexpected untyped expression: %s", name.c_str() );
479 assertf( ! expr->get_args().empty(), "Cannot get function name from dereference with no arguments" );
480 return funcName( expr->get_args().front() );
481 }
482
483 std::string funcName( Expression * func ) {
484 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
485 return nameExpr->get_name();
486 } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
487 return varExpr->get_var()->get_name();
488 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
489 return funcName( castExpr->get_arg() );
490 } else if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( func ) ) {
491 return memberExpr->get_member()->get_name();
492 } else if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * > ( func ) ) {
493 return funcName( memberExpr->get_member() );
494 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( func ) ) {
495 return handleDerefName( untypedExpr );
496 } else if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( func ) ) {
497 return handleDerefName( appExpr );
498 } else if ( ConstructorExpr * ctorExpr = dynamic_cast< ConstructorExpr * >( func ) ) {
499 return funcName( getCallArg( ctorExpr->get_callExpr(), 0 ) );
500 } else {
501 assertf( false, "Unexpected expression type being called as a function in call expression: %s", toString( func ).c_str() );
502 }
503 }
504 }
505
506 std::string getFunctionName( Expression * expr ) {
507 // there's some unforunate overlap here with getCalledFunction. Ideally this would be able to use getCalledFunction and
508 // return the name of the DeclarationWithType, but this needs to work for NameExpr and UntypedMemberExpr, where getCalledFunction
509 // can't possibly do anything reasonable.
510 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
511 return funcName( appExpr->get_function() );
512 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
513 return funcName( untypedExpr->get_function() );
514 } else {
515 std::cerr << expr << std::endl;
516 assertf( false, "Unexpected expression type passed to getFunctionName" );
517 }
518 }
519
520 Type * getPointerBase( Type * type ) {
521 if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
522 return ptrType->get_base();
523 } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
524 return arrayType->get_base();
525 } else if ( ReferenceType * refType = dynamic_cast< ReferenceType * >( type ) ) {
526 return refType->get_base();
527 } else {
528 return nullptr;
529 }
530 }
531
532 Type * isPointerType( Type * type ) {
533 if ( getPointerBase( type ) ) return type;
534 else return nullptr;
535 }
536
537 ApplicationExpr * createBitwiseAssignment( Expression * dst, Expression * src ) {
538 static FunctionDecl * assign = nullptr;
539 if ( ! assign ) {
540 // temporary? Generate a fake assignment operator to represent bitwise assignments.
541 // This operator could easily exist as a real function, but it's tricky because nothing should resolve to this function.
542 TypeDecl * td = new TypeDecl( "T", noStorageClasses, nullptr, TypeDecl::Dtype, true );
543 assign = new FunctionDecl( "?=?", noStorageClasses, LinkageSpec::Intrinsic, SymTab::genAssignType( new TypeInstType( noQualifiers, td->name, td ) ), nullptr );
544 }
545 if ( dynamic_cast< ReferenceType * >( dst->result ) ) {
546 dst = new AddressExpr( dst );
547 } else {
548 dst = new CastExpr( dst, new ReferenceType( noQualifiers, dst->result->clone() ) );
549 }
550 if ( dynamic_cast< ReferenceType * >( src->result ) ) {
551 src = new CastExpr( src, new ReferenceType( noQualifiers, src->result->stripReferences()->clone() ) );
552 }
553 return new ApplicationExpr( VariableExpr::functionPointer( assign ), { dst, src } );
554 }
555
556 class ConstExprChecker : public Visitor {
557 public:
558 ConstExprChecker() : isConstExpr( true ) {}
559
560 using Visitor::visit;
561
562 virtual void visit( ApplicationExpr * ) { isConstExpr = false; }
563 virtual void visit( UntypedExpr * ) { isConstExpr = false; }
564 virtual void visit( NameExpr * ) { isConstExpr = false; }
565 // virtual void visit( CastExpr *castExpr ) { isConstExpr = false; }
566 virtual void visit( AddressExpr *addressExpr ) {
567 // address of a variable or member expression is constexpr
568 Expression * arg = addressExpr->get_arg();
569 if ( ! dynamic_cast< NameExpr * >( arg) && ! dynamic_cast< VariableExpr * >( arg ) && ! dynamic_cast< MemberExpr * >( arg ) && ! dynamic_cast< UntypedMemberExpr * >( arg ) ) isConstExpr = false;
570 }
571 virtual void visit( UntypedMemberExpr * ) { isConstExpr = false; }
572 virtual void visit( MemberExpr * ) { isConstExpr = false; }
573 virtual void visit( VariableExpr * ) { isConstExpr = false; }
574 // these might be okay?
575 // virtual void visit( SizeofExpr *sizeofExpr );
576 // virtual void visit( AlignofExpr *alignofExpr );
577 // virtual void visit( UntypedOffsetofExpr *offsetofExpr );
578 // virtual void visit( OffsetofExpr *offsetofExpr );
579 // virtual void visit( OffsetPackExpr *offsetPackExpr );
580 // virtual void visit( AttrExpr *attrExpr );
581 // virtual void visit( CommaExpr *commaExpr );
582 // virtual void visit( LogicalExpr *logicalExpr );
583 // virtual void visit( ConditionalExpr *conditionalExpr );
584 virtual void visit( TypeExpr * ) { isConstExpr = false; }
585 virtual void visit( AsmExpr * ) { isConstExpr = false; }
586 virtual void visit( UntypedValofExpr * ) { isConstExpr = false; }
587 virtual void visit( CompoundLiteralExpr * ) { isConstExpr = false; }
588 virtual void visit( UntypedTupleExpr * ) { isConstExpr = false; }
589 virtual void visit( TupleExpr * ) { isConstExpr = false; }
590 virtual void visit( TupleAssignExpr * ) { isConstExpr = false; }
591
592 bool isConstExpr;
593 };
594
595 bool isConstExpr( Expression * expr ) {
596 if ( expr ) {
597 ConstExprChecker checker;
598 expr->accept( checker );
599 return checker.isConstExpr;
600 }
601 return true;
602 }
603
604 bool isConstExpr( Initializer * init ) {
605 if ( init ) {
606 ConstExprChecker checker;
607 init->accept( checker );
608 return checker.isConstExpr;
609 } // if
610 // for all intents and purposes, no initializer means const expr
611 return true;
612 }
613
614 bool isConstructor( const std::string & str ) { return str == "?{}"; }
615 bool isDestructor( const std::string & str ) { return str == "^?{}"; }
616 bool isAssignment( const std::string & str ) { return str == "?=?"; }
617 bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
618 bool isCtorDtorAssign( const std::string & str ) { return isCtorDtor( str ) || isAssignment( str ); }
619
620 FunctionDecl * isCopyFunction( Declaration * decl, const std::string & fname ) {
621 FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl );
622 if ( ! function ) return nullptr;
623 if ( function->name != fname ) return nullptr;
624 FunctionType * ftype = function->type;
625 if ( ftype->parameters.size() != 2 ) return nullptr;
626
627 Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
628 Type * t2 = ftype->parameters.back()->get_type();
629 assert( t1 );
630
631 if ( ResolvExpr::typesCompatibleIgnoreQualifiers( t1, t2, SymTab::Indexer() ) ) {
632 return function;
633 } else {
634 return nullptr;
635 }
636 }
637
638 FunctionDecl * isAssignment( Declaration * decl ) {
639 return isCopyFunction( decl, "?=?" );
640 }
641 FunctionDecl * isDestructor( Declaration * decl ) {
642 if ( isDestructor( decl->get_name() ) ) {
643 return dynamic_cast< FunctionDecl * >( decl );
644 }
645 return nullptr;
646 }
647 FunctionDecl * isDefaultConstructor( Declaration * decl ) {
648 if ( isConstructor( decl->name ) ) {
649 if ( FunctionDecl * func = dynamic_cast< FunctionDecl * >( decl ) ) {
650 if ( func->type->parameters.size() == 1 ) {
651 return func;
652 }
653 }
654 }
655 return nullptr;
656 }
657 FunctionDecl * isCopyConstructor( Declaration * decl ) {
658 return isCopyFunction( decl, "?{}" );
659 }
660}
Note: See TracBrowser for help on using the repository browser.