source: src/InitTweak/FixInit.cpp@ a5e2786f

Last change on this file since a5e2786f was 0bf03ba2, checked in by Michael Brooks <mlbrooks@…>, 9 months ago

Remove warnings due to unused parameters in generated code for zero-length ttype instantiations.

  • Property mode set to 100644
File size: 54.4 KB
Line 
1#include "FixInit.hpp"
2
3#include <stddef.h> // for NULL
4#include <algorithm> // for set_difference, copy_if
5#include <cassert> // for assert, strict_dynamic_cast
6#include <iostream> // for operator<<, ostream, basic_ost...
7#include <iterator> // for insert_iterator, back_inserter
8#include <list> // for _List_iterator, list, list<>::...
9#include <map> // for _Rb_tree_iterator, _Rb_tree_co...
10#include <memory> // for allocator_traits<>::value_type
11#include <set> // for set, set<>::value_type
12#include <unordered_map> // for unordered_map, unordered_map<>...
13#include <unordered_set> // for unordered_set
14#include <utility> // for pair
15
16#include "AST/DeclReplacer.hpp"
17#include "AST/Expr.hpp"
18#include "AST/Inspect.hpp" // for getFunction, getPointerBase, g...
19#include "AST/Node.hpp"
20#include "AST/Pass.hpp"
21#include "AST/Print.hpp"
22#include "AST/SymbolTable.hpp"
23#include "AST/Type.hpp"
24#include "CodeGen/OperatorTable.hpp" // for isConstructor, isCtorDtor, isD...
25#include "Common/SemanticError.hpp" // for SemanticError
26#include "Common/ToString.hpp" // for toCString
27#include "Common/UniqueName.hpp" // for UniqueName
28#include "FixGlobalInit.hpp" // for fixGlobalInit
29#include "GenInit.hpp" // for genCtorDtor
30#include "GenPoly/GenPoly.hpp" // for getFunctionType
31#include "ResolvExpr/Resolver.hpp" // for findVoidExpression
32#include "ResolvExpr/Unify.hpp" // for typesCompatible
33#include "SymTab/GenImplicitCall.hpp" // for genImplicitCall
34
35bool ctordtorp = false; // print all debug
36bool ctorp = false; // print ctor debug
37bool cpctorp = false; // print copy ctor debug
38bool dtorp = false; // print dtor debug
39#define PRINT( text ) if ( ctordtorp ) { text }
40#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
41#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
42
43namespace InitTweak {
44
45namespace {
46
47// Shallow copy the pointer list for return.
48std::vector<ast::ptr<ast::TypeDecl>> getGenericParams( const ast::Type * t ) {
49 if ( auto inst = dynamic_cast<const ast::StructInstType *>( t ) ) {
50 return inst->base->params;
51 } else if ( auto inst = dynamic_cast<const ast::UnionInstType *>( t ) ) {
52 return inst->base->params;
53 }
54 return {};
55}
56
57/// Given type T, generate type of default ctor/dtor, i.e. function type void (*) (T &).
58ast::FunctionDecl * genDefaultFunc(
59 const CodeLocation loc,
60 const std::string fname,
61 const ast::Type * paramType,
62 bool maybePolymorphic = true) {
63 std::vector<ast::ptr<ast::TypeDecl>> typeParams;
64 if ( maybePolymorphic ) typeParams = getGenericParams( paramType );
65 auto dstParam = new ast::ObjectDecl( loc,
66 "_dst",
67 new ast::ReferenceType( paramType ),
68 nullptr,
69 {},
70 ast::Linkage::Cforall
71 );
72 dstParam->attributes.push_back( new ast::Attribute( "unused" ) );
73 return new ast::FunctionDecl( loc,
74 fname,
75 std::move(typeParams),
76 {},
77 {dstParam},
78 {},
79 new ast::CompoundStmt(loc),
80 {},
81 ast::Linkage::Cforall
82 );
83}
84
85struct SelfAssignChecker {
86 void previsit( const ast::ApplicationExpr * appExpr );
87};
88
89struct StmtExprResult {
90 const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
91};
92
93/// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
94/// function calls need their parameters to be copy constructed
95struct InsertImplicitCalls : public ast::WithShortCircuiting {
96 const ast::Expr * postvisit( const ast::ApplicationExpr * appExpr );
97
98 // only handles each UniqueExpr once
99 // if order of visit does not change, this should be safe
100 void previsit (const ast::UniqueExpr *);
101
102 std::unordered_set<decltype(ast::UniqueExpr::id)> visitedIds;
103};
104
105/// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
106/// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
107/// arguments and return value temporaries
108struct ResolveCopyCtors final : public ast::WithGuards, public ast::WithStmtsToAdd, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithVisitorRef<ResolveCopyCtors>, public ast::WithConstTranslationUnit {
109 const ast::Expr * postvisit( const ast::ImplicitCopyCtorExpr * impCpCtorExpr );
110 const ast::StmtExpr * previsit( const ast::StmtExpr * stmtExpr );
111 const ast::UniqueExpr * previsit( const ast::UniqueExpr * unqExpr );
112
113 /// handles distant mutations of environment manually.
114 /// WithConstTypeSubstitution cannot remember where the environment is from
115
116 /// MUST be called at start of overload previsit
117 void previsit( const ast::Expr * expr);
118 /// MUST be called at return of overload postvisit
119 const ast::Expr * postvisit(const ast::Expr * expr);
120
121 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
122 const ast::Expr * makeCtorDtor( const std::string & fname, const ast::ObjectDecl * var, const ast::Expr * cpArg = nullptr );
123 /// true if type does not need to be copy constructed to ensure correctness
124 bool skipCopyConstruct( const ast::Type * type );
125 ast::ptr< ast::Expr > copyConstructArg( const ast::Expr * arg, const ast::ImplicitCopyCtorExpr * impCpCtorExpr, const ast::Type * formal );
126 ast::Expr * destructRet( const ast::ObjectDecl * ret, const ast::Expr * arg );
127private:
128 /// hack to implement WithTypeSubstitution while conforming to mutation safety.
129 ast::TypeSubstitution * env = nullptr;
130 bool envModified = false;
131};
132
133/// collects constructed object decls - used as a base class
134struct ObjDeclCollector : public ast::WithGuards, public ast::WithShortCircuiting {
135 // use ordered data structure to maintain ordering for set_difference and for consistent error messages
136 typedef std::list< const ast::ObjectDecl * > ObjectSet;
137 void previsit( const ast::CompoundStmt *compoundStmt );
138 void previsit( const ast::DeclStmt *stmt );
139
140 // don't go into other functions
141 void previsit( const ast::FunctionDecl * ) { visit_children = false; }
142
143protected:
144 ObjectSet curVars;
145};
146
147// debug
148template<typename ObjectSet>
149struct PrintSet {
150 PrintSet( const ObjectSet & objs ) : objs( objs ) {}
151 const ObjectSet & objs;
152};
153template<typename ObjectSet>
154PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); }
155template<typename ObjectSet>
156std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) {
157 out << "{ ";
158 for ( auto & obj : set.objs ) {
159 out << obj->name << ", " ;
160 } // for
161 out << " }";
162 return out;
163}
164
165struct LabelFinder final : public ObjDeclCollector {
166 typedef std::map< std::string, ObjectSet > LabelMap;
167 // map of Label -> live variables at that label
168 LabelMap vars;
169
170 typedef ObjDeclCollector Parent;
171 using Parent::previsit;
172 void previsit( const ast::Stmt * stmt );
173
174 void previsit( const ast::CompoundStmt *compoundStmt );
175 void previsit( const ast::DeclStmt *stmt );
176};
177
178/// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
179/// (currently by FixInit)
180struct InsertDtors final : public ObjDeclCollector, public ast::WithStmtsToAdd {
181 InsertDtors( ast::Pass<LabelFinder> & finder ) : finder( finder ), labelVars( finder.core.vars ) {}
182
183 typedef ObjDeclCollector Parent;
184 using Parent::previsit;
185
186 void previsit( const ast::FunctionDecl * funcDecl );
187
188 void previsit( const ast::BranchStmt * stmt );
189private:
190 void handleGoto( const ast::BranchStmt * stmt );
191
192 ast::Pass<LabelFinder> & finder;
193 LabelFinder::LabelMap & labelVars;
194};
195
196/// expand each object declaration to use its constructor after it is declared.
197struct FixInit : public ast::WithStmtsToAdd {
198 static void fixInitializers( ast::TranslationUnit &translationUnit );
199
200 const ast::DeclWithType * postvisit( const ast::ObjectDecl *objDecl );
201
202 std::list< ast::ptr< ast::Decl > > staticDtorDecls;
203};
204
205/// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
206/// for any member that is missing a corresponding ctor/dtor call.
207/// error if a member is used before constructed
208struct GenStructMemberCalls final : public ast::WithGuards, public ast::WithShortCircuiting, public ast::WithSymbolTable, public ast::WithVisitorRef<GenStructMemberCalls>, public ast::WithConstTranslationUnit {
209 void previsit( const ast::FunctionDecl * funcDecl );
210 const ast::DeclWithType * postvisit( const ast::FunctionDecl * funcDecl );
211
212 void previsit( const ast::MemberExpr * memberExpr );
213 void previsit( const ast::ApplicationExpr * appExpr );
214
215 /// Note: this post mutate used to be in a separate visitor. If this pass breaks, one place to examine is whether it is
216 /// okay for this part of the recursion to occur alongside the rest.
217 const ast::Expr * postvisit( const ast::UntypedExpr * expr );
218
219 SemanticErrorException errors;
220private:
221 template< typename... Params >
222 void emit( CodeLocation, const Params &... params );
223
224 ast::FunctionDecl * function = nullptr;
225 std::set< const ast::DeclWithType * > unhandled;
226 std::map< const ast::DeclWithType *, CodeLocation > usedUninit;
227 const ast::ObjectDecl * thisParam = nullptr;
228 bool isCtor = false; // true if current function is a constructor
229 const ast::StructDecl * structDecl = nullptr;
230};
231
232/// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
233struct FixCtorExprs final : public ast::WithDeclsToAdd, public ast::WithSymbolTable, public ast::WithShortCircuiting, public ast::WithConstTranslationUnit {
234 const ast::Expr * postvisit( const ast::ConstructorExpr * ctorExpr );
235};
236
237/// add CompoundStmts around top-level expressions so that temporaries are destroyed in the correct places.
238struct SplitExpressions : public ast::WithShortCircuiting {
239 ast::Stmt * postvisit( const ast::ExprStmt * stmt );
240 void previsit( const ast::TupleAssignExpr * expr );
241};
242
243/// find and return the destructor used in `input`. If `input` is not a simple destructor call, generate a thunk
244/// that wraps the destructor, insert it into `stmtsToAdd` and return the new function declaration
245const ast::DeclWithType * getDtorFunc( const ast::ObjectDecl * objDecl, const ast::Stmt * input, std::list< ast::ptr<ast::Stmt> > & stmtsToAdd ) {
246 const CodeLocation loc = input->location;
247 assert( input );
248 auto matches = collectCtorDtorCalls( input );
249
250 // The simple case requires a direct call and only one destructor call.
251 if ( dynamic_cast< const ast::ExprStmt * >( input ) && matches.size() == 1 ) {
252 auto func = getFunction( matches.front() );
253 assertf( func, "getFunction failed to find function in %s", toString( matches.front() ).c_str() );
254
255 // cleanup argument must be a function, not an object (including function pointer)
256 if ( auto dtorFunc = dynamic_cast< const ast::FunctionDecl * > ( func ) ) {
257 if ( dtorFunc->type->forall.empty() ) {
258 // simple case where the destructor is a monomorphic function call - can simply
259 // use that function as the cleanup function.
260 return func;
261 }
262 }
263 }
264
265 // otherwise the cleanup is more complicated - need to build a single argument cleanup function that
266 // wraps the more complicated code.
267 static UniqueName dtorNamer( "__cleanup_dtor" );
268 std::string name = dtorNamer.newName();
269 ast::FunctionDecl * dtorFunc = genDefaultFunc( loc, name, objDecl->type->stripReferences(), false );
270 stmtsToAdd.push_back( new ast::DeclStmt(loc, dtorFunc ) );
271
272 // the original code contains uses of objDecl - replace them with the newly generated 'this' parameter.
273 const ast::ObjectDecl * thisParam = getParamThis( dtorFunc );
274 const ast::Expr * replacement = new ast::VariableExpr( loc, thisParam );
275
276 auto base = replacement->result->stripReferences();
277 if ( dynamic_cast< const ast::ArrayType * >( base ) || dynamic_cast< const ast::TupleType * > ( base ) ) {
278 // need to cast away reference for array types, since the destructor is generated without the reference type,
279 // and for tuple types since tuple indexing does not work directly on a reference
280 replacement = new ast::CastExpr( replacement, base );
281 }
282 auto dtor = ast::DeclReplacer::replace( input, ast::DeclReplacer::ExprMap{ std::make_pair( objDecl, replacement ) } );
283 auto mutStmts = dtorFunc->stmts.get_and_mutate();
284 mutStmts->push_back(strict_dynamic_cast<const ast::Stmt *>( dtor ));
285 dtorFunc->stmts = mutStmts;
286
287 return dtorFunc;
288}
289
290void FixInit::fixInitializers( ast::TranslationUnit & translationUnit ) {
291 ast::Pass<FixInit> fixer;
292
293 // can't use mutateAll, because need to insert declarations at top-level
294 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
295 SemanticErrorException errors;
296 for ( auto i = translationUnit.decls.begin(); i != translationUnit.decls.end(); ++i ) {
297 try {
298 *i = (*i)->accept(fixer);
299 translationUnit.decls.splice( i, fixer.core.staticDtorDecls );
300 } catch( SemanticErrorException &e ) {
301 errors.append( e );
302 } // try
303 } // for
304 errors.throwIfNonEmpty();
305}
306
307const ast::StmtExpr * StmtExprResult::previsit( const ast::StmtExpr * stmtExpr ) {
308 assert( stmtExpr->result );
309 if ( stmtExpr->result->isVoid() ) return stmtExpr;
310
311 auto mutExpr = mutate( stmtExpr );
312 const ast::CompoundStmt * body = mutExpr->stmts;
313 assert( !body->kids.empty() );
314 mutExpr->resultExpr = body->kids.back().strict_as<ast::ExprStmt>();
315 return mutExpr;
316}
317
318ast::Stmt * SplitExpressions::postvisit( const ast::ExprStmt * stmt ) {
319 // wrap each top-level ExprStmt in a block so that destructors for argument and return temporaries are destroyed
320 // in the correct places
321 return new ast::CompoundStmt( stmt->location, { stmt } );
322}
323
324void SplitExpressions::previsit( const ast::TupleAssignExpr * ) {
325 // don't do this within TupleAssignExpr, since it is already broken up into multiple expressions
326 visit_children = false;
327}
328
329// Relatively simple structural comparison for expressions, needed to determine
330// if two expressions are "the same" (used to determine if self assignment occurs)
331struct StructuralChecker {
332 // Strip all casts and then dynamic_cast.
333 template<typename T>
334 static const T * cast( const ast::Expr * expr ) {
335 // this might be too permissive. It's possible that only particular casts are relevant.
336 while ( auto cast = dynamic_cast< const ast::CastExpr * >( expr ) ) {
337 expr = cast->arg;
338 }
339 return dynamic_cast< const T * >( expr );
340 }
341
342 void previsit( const ast::Expr * ) {
343 // anything else does not qualify
344 result = false;
345 }
346
347 // ignore casts
348 void previsit( const ast::CastExpr * ) {}
349
350 void previsit( const ast::MemberExpr * memExpr ) {
351 if ( auto otherMember = cast< ast::MemberExpr >( other ) ) {
352 if ( otherMember->member == memExpr->member ) {
353 other = otherMember->aggregate;
354 return;
355 }
356 }
357 result = false;
358 }
359
360 void previsit( const ast::VariableExpr * varExpr ) {
361 if ( auto otherVar = cast< ast::VariableExpr >( other ) ) {
362 if ( otherVar->var == varExpr->var ) {
363 return;
364 }
365 }
366 result = false;
367 }
368
369 void previsit( const ast::AddressExpr * ) {
370 if ( auto addrExpr = cast< ast::AddressExpr >( other ) ) {
371 other = addrExpr->arg;
372 return;
373 }
374 result = false;
375 }
376
377 const ast::Expr * other;
378 bool result = true;
379 StructuralChecker( const ast::Expr * other ) : other(other) {}
380};
381
382bool structurallySimilar( const ast::Expr * e1, const ast::Expr * e2 ) {
383 return ast::Pass<StructuralChecker>::read( e1, e2 );
384}
385
386void SelfAssignChecker::previsit( const ast::ApplicationExpr * appExpr ) {
387 auto function = getFunction( appExpr );
388 // Doesn't use isAssignment, because ?+=?, etc. should not count as self-assignment.
389 if ( function->name == "?=?" && appExpr->args.size() == 2
390 // Check for structural similarity (same variable use, ignore casts, etc.
391 // (but does not look too deeply, anything looking like a function is off limits).
392 && structurallySimilar( appExpr->args.front(), appExpr->args.back() ) ) {
393 SemanticWarning( appExpr->location, Warning::SelfAssignment, toCString( appExpr->args.front() ) );
394 }
395}
396
397const ast::Expr * InsertImplicitCalls::postvisit( const ast::ApplicationExpr * appExpr ) {
398 if ( auto function = appExpr->func.as<ast::VariableExpr>() ) {
399 if ( function->var->linkage.is_builtin ) {
400 // optimization: don't need to copy construct in order to call intrinsic functions
401 return appExpr;
402 } else if ( auto funcDecl = function->var.as<ast::DeclWithType>() ) {
403 auto ftype = dynamic_cast< const ast::FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
404 assertf( ftype, "Function call without function type: %s", toString( funcDecl ).c_str() );
405 if ( CodeGen::isConstructor( funcDecl->name ) && ftype->params.size() == 2 ) {
406 auto t1 = getPointerBase( ftype->params.front() );
407 auto t2 = ftype->params.back();
408 assert( t1 );
409
410 if ( ResolvExpr::typesCompatible( t1, t2 ) ) {
411 // optimization: don't need to copy construct in order to call a copy constructor
412 return appExpr;
413 } // if
414 } else if ( CodeGen::isDestructor( funcDecl->name ) ) {
415 // correctness: never copy construct arguments to a destructor
416 return appExpr;
417 } // if
418 } // if
419 } // if
420 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
421
422 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
423 ast::ptr<ast::TypeSubstitution> tmp = appExpr->env;
424 auto mutExpr = mutate(appExpr);
425 mutExpr->env = nullptr;
426
427 auto expr = new ast::ImplicitCopyCtorExpr( appExpr->location, mutExpr );
428 // Move the type substitution to the new top-level. The substitution
429 // is needed to obtain the type of temporary variables so that copy
430 // constructor calls can be resolved.
431 expr->env = tmp;
432 return expr;
433}
434
435void ResolveCopyCtors::previsit(const ast::Expr * expr) {
436 if ( nullptr == expr->env ) {
437 return;
438 }
439 GuardValue( env ) = expr->env->clone();
440 GuardValue( envModified ) = false;
441}
442
443const ast::Expr * ResolveCopyCtors::postvisit(const ast::Expr * expr) {
444 // No local environment, skip.
445 if ( nullptr == expr->env ) {
446 return expr;
447 // Environment was modified, mutate and replace.
448 } else if ( envModified ) {
449 auto mutExpr = mutate(expr);
450 mutExpr->env = env;
451 return mutExpr;
452 // Environment was not mutated, delete the shallow copy before guard.
453 } else {
454 delete env;
455 return expr;
456 }
457}
458
459bool ResolveCopyCtors::skipCopyConstruct( const ast::Type * type ) { return ! isConstructable( type ); }
460
461const ast::Expr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, const ast::ObjectDecl * var, const ast::Expr * cpArg ) {
462 assert( var );
463 assert( var->isManaged() );
464 assert( !cpArg || cpArg->isManaged() );
465 // arrays are not copy constructed, so this should always be an ExprStmt
466 ast::ptr< ast::Stmt > stmt = genCtorDtor(var->location, fname, var, cpArg );
467 assertf( stmt, "ResolveCopyCtors: genCtorDtor returned nullptr: %s / %s / %s", fname.c_str(), toString( var ).c_str(), toString( cpArg ).c_str() );
468 auto exprStmt = stmt.strict_as<ast::ImplicitCtorDtorStmt>()->callStmt.strict_as<ast::ExprStmt>();
469 ast::ptr<ast::Expr> untyped = exprStmt->expr; // take ownership of expr
470
471 // resolve copy constructor
472 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
473 // (VariableExpr and already resolved expression)
474 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
475 ast::ptr<ast::Expr> resolved = ResolvExpr::findVoidExpression(untyped, { symtab, transUnit().global } );
476 assert( resolved );
477 if ( resolved->env ) {
478 // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
479 env->add( *resolved->env );
480 envModified = true;
481 auto mut = mutate(resolved.get());
482 assertf(mut == resolved.get(), "newly resolved expression must be unique");
483 mut->env = nullptr;
484 } // if
485 if ( auto assign = resolved.as<ast::TupleAssignExpr>() ) {
486 // fix newly generated StmtExpr
487 previsit( assign->stmtExpr );
488 }
489 return resolved.release();
490}
491
492ast::ptr<ast::Expr> ResolveCopyCtors::copyConstructArg(
493 const ast::Expr * arg, const ast::ImplicitCopyCtorExpr * impCpCtorExpr, const ast::Type * formal )
494{
495 static UniqueName tempNamer("_tmp_cp");
496 const CodeLocation loc = impCpCtorExpr->location;
497 // CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
498 assert( arg->result );
499 ast::ptr<ast::Type> result = arg->result;
500 if ( skipCopyConstruct( result ) ) return arg; // skip certain non-copyable types
501
502 // type may involve type variables, so apply type substitution to get temporary variable's actual type,
503 // since result type may not be substituted (e.g., if the type does not appear in the parameter list)
504 // Use applyFree so that types bound in function pointers are not substituted, e.g. in forall(dtype T) void (*)(T).
505
506 // xxx - this originally mutates arg->result in place. is it correct?
507 assert( env );
508 result = env->applyFree( result.get() ).node;
509 auto mutResult = result.get_and_mutate();
510 mutResult->set_const(false);
511
512 auto mutArg = mutate(arg);
513 mutArg->result = mutResult;
514
515 ast::ptr<ast::Expr> guard = mutArg;
516
517 ast::ptr<ast::ObjectDecl> tmp = new ast::ObjectDecl(loc, "__tmp", mutResult, nullptr );
518
519 // create and resolve copy constructor
520 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
521 auto cpCtor = makeCtorDtor( "?{}", tmp, mutArg );
522
523 if ( auto appExpr = dynamic_cast< const ast::ApplicationExpr * >( cpCtor ) ) {
524 // if the chosen constructor is intrinsic, the copy is unnecessary, so
525 // don't create the temporary and don't call the copy constructor
526 auto function = appExpr->func.strict_as<ast::VariableExpr>();
527 if ( function->var->linkage == ast::Linkage::Intrinsic ) {
528 // arguments that need to be boxed need a temporary regardless of whether the copy constructor is intrinsic,
529 // so that the object isn't changed inside of the polymorphic function
530 if ( ! GenPoly::needsBoxing( formal, result, impCpCtorExpr->callExpr, env ) ) {
531 // xxx - should arg->result be mutated? see comment above.
532 return guard;
533 }
534 }
535 }
536
537 // set a unique name for the temporary once it's certain the call is necessary
538 auto mut = tmp.get_and_mutate();
539 assertf (mut == tmp, "newly created ObjectDecl must be unique");
540 mut->name = tempNamer.newName();
541
542 // replace argument to function call with temporary
543 stmtsToAddBefore.push_back( new ast::DeclStmt(loc, tmp ) );
544 arg = cpCtor;
545 return destructRet( tmp, arg );
546}
547
548ast::Expr * ResolveCopyCtors::destructRet( const ast::ObjectDecl * ret, const ast::Expr * arg ) {
549 auto global = transUnit().global;
550 // TODO: refactor code for generating cleanup attribute, since it's common and reused in ~3-4 places
551 // check for existing cleanup attribute before adding another(?)
552 // need to add __Destructor for _tmp_cp variables as well
553
554 assertf( global.dtorStruct, "Destructor generation requires __Destructor definition." );
555 assertf( global.dtorStruct->members.size() == 2, "__Destructor definition does not have expected fields." );
556 assertf( global.dtorDestroy, "Destructor generation requires __destroy_Destructor." );
557
558 const CodeLocation & loc = ret->location;
559
560 // generate a __Destructor for ret that calls the destructor
561 auto res = makeCtorDtor( "^?{}", ret );
562 auto dtor = mutate(res);
563
564 // if the chosen destructor is intrinsic, elide the generated dtor handler
565 if ( arg && isIntrinsicCallExpr( dtor ) ) {
566 return new ast::CommaExpr(loc, arg, new ast::VariableExpr(loc, ret ) );
567 }
568
569 if ( nullptr == dtor->env && nullptr != env ) {
570 dtor->env = ast::shallowCopy( env );
571 }
572 auto dtorFunc = getDtorFunc( ret, new ast::ExprStmt(loc, dtor ), stmtsToAddBefore );
573
574 auto dtorStructType = new ast::StructInstType( global.dtorStruct );
575
576 // what does this do???
577 dtorStructType->params.push_back( new ast::TypeExpr(loc, new ast::VoidType() ) );
578
579 // cast destructor pointer to void (*)(void *), to silence GCC incompatible pointer warnings
580 auto dtorFtype = new ast::FunctionType();
581 dtorFtype->params.push_back( new ast::PointerType(new ast::VoidType( ) ) );
582 auto dtorType = new ast::PointerType( dtorFtype );
583
584 static UniqueName namer( "_ret_dtor" );
585 auto retDtor = new ast::ObjectDecl(loc, namer.newName(), dtorStructType, new ast::ListInit(loc, { new ast::SingleInit(loc, ast::ConstantExpr::null(loc) ), new ast::SingleInit(loc, new ast::CastExpr( new ast::VariableExpr(loc, dtorFunc ), dtorType ) ) } ) );
586 retDtor->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr(loc, global.dtorDestroy ) } ) );
587 stmtsToAddBefore.push_back( new ast::DeclStmt(loc, retDtor ) );
588
589 if ( arg ) {
590 auto member = new ast::MemberExpr(loc, global.dtorStruct->members.front().strict_as<ast::DeclWithType>(), new ast::VariableExpr(loc, retDtor ) );
591 auto object = new ast::CastExpr( new ast::AddressExpr( new ast::VariableExpr(loc, ret ) ), new ast::PointerType(new ast::VoidType() ) );
592 ast::Expr * assign = createBitwiseAssignment( member, object );
593 return new ast::CommaExpr(loc, new ast::CommaExpr(loc, arg, assign ), new ast::VariableExpr(loc, ret ) );
594 }
595 return nullptr;
596}
597
598const ast::Expr * ResolveCopyCtors::postvisit( const ast::ImplicitCopyCtorExpr *impCpCtorExpr ) {
599 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
600
601 ast::ApplicationExpr * appExpr = mutate(impCpCtorExpr->callExpr.get());
602 const ast::ObjectDecl * returnDecl = nullptr;
603 const CodeLocation loc = appExpr->location;
604
605 // take each argument and attempt to copy construct it.
606 auto ftype = GenPoly::getFunctionType( appExpr->func->result );
607 assert( ftype );
608 auto & params = ftype->params;
609 auto iter = params.begin();
610 for ( auto & arg : appExpr->args ) {
611 const ast::Type * formal = nullptr;
612 // Do not copy construct C-style variadic arguments.
613 if ( iter != params.end() ) {
614 formal = *iter++;
615 }
616
617 arg = copyConstructArg( arg, impCpCtorExpr, formal );
618 } // for
619
620 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
621 // initialized with the return value and is destructed later
622 // xxx - handle named return values?
623 const ast::Type * result = appExpr->result;
624 if ( ! result->isVoid() ) {
625 static UniqueName retNamer("_tmp_cp_ret");
626 auto subResult = env->apply( result ).node;
627 auto ret = new ast::ObjectDecl(loc, retNamer.newName(), subResult, nullptr );
628 auto mutType = mutate(ret->type.get());
629 mutType->set_const( false );
630 ret->type = mutType;
631 returnDecl = ret;
632 stmtsToAddBefore.push_back( new ast::DeclStmt(loc, ret ) );
633 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
634 } // for
635 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
636 // ------------------------------------------------------
637
638 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
639
640 // detach fields from wrapper node so that it can be deleted without deleting too much
641
642 // xxx - actual env might be somewhere else, need to keep invariant
643
644 // deletion of wrapper should be handled by pass template now
645
646 assert (appExpr->env == nullptr);
647 appExpr->env = impCpCtorExpr->env;
648
649 if ( returnDecl ) {
650 ast::Expr * assign = createBitwiseAssignment( new ast::VariableExpr(loc, returnDecl ), appExpr );
651 if ( ! dynamic_cast< const ast::ReferenceType * >( result ) ) {
652 // destructing reference returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
653 assign = destructRet( returnDecl, assign );
654 assert(assign);
655 } else {
656 assign = new ast::CommaExpr(loc, assign, new ast::VariableExpr(loc, returnDecl ) );
657 }
658 // move env from appExpr to retExpr
659 assign->env = appExpr->env;
660 // actual env is handled by common routine that replaces WithTypeSubstitution
661 return postvisit((const ast::Expr *)assign);
662 } else {
663 return postvisit((const ast::Expr *)appExpr);
664 } // if
665}
666
667const ast::StmtExpr * ResolveCopyCtors::previsit( const ast::StmtExpr * _stmtExpr ) {
668 // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
669 // since temporaries can be shared across sub-expressions, e.g.
670 // [A, A] f(); // decl
671 // g([A] x, [A] y); // decl
672 // g(f()); // call
673 // f is executed once, so the return temporary is shared across the tuple constructors for x and y.
674 // Explicitly mutating children instead of mutating the inner compound statement forces the temporaries to be added
675 // to the outer context, rather than inside of the statement expression.
676
677 // call the common routine that replaces WithTypeSubstitution
678 previsit((const ast::Expr *) _stmtExpr);
679
680 visit_children = false;
681 const CodeLocation loc = _stmtExpr->location;
682
683 assert( env );
684
685 symtab.enterScope();
686 // visit all statements
687 auto stmtExpr = mutate(_stmtExpr);
688 auto mutStmts = mutate(stmtExpr->stmts.get());
689
690 auto & stmts = mutStmts->kids;
691 for ( auto & stmt : stmts ) {
692 stmt = stmt->accept( *visitor );
693 } // for
694 stmtExpr->stmts = mutStmts;
695 symtab.leaveScope();
696
697 assert( stmtExpr->result );
698 if ( stmtExpr->result->isVoid() ) {
699 assert( stmtExpr->returnDecls.empty() );
700 assert( stmtExpr->dtors.empty() );
701
702 return stmtExpr;
703 }
704
705 static UniqueName retNamer("_tmp_stmtexpr_ret");
706
707 auto result = env->apply( stmtExpr->result.get() ).node;
708 if ( ! InitTweak::isConstructable( result ) ) {
709 return stmtExpr;
710 }
711 auto mutResult = result.get_and_mutate();
712 mutResult->set_const(false);
713
714 // create variable that will hold the result of the stmt expr
715 auto ret = new ast::ObjectDecl(loc, retNamer.newName(), mutResult, nullptr );
716 stmtsToAddBefore.push_back( new ast::DeclStmt(loc, ret ) );
717
718 assertf(
719 stmtExpr->resultExpr,
720 "Statement-Expression should have a resulting expression at %s:%d",
721 stmtExpr->location.filename.c_str(),
722 stmtExpr->location.first_line
723 );
724
725 const ast::ExprStmt * last = stmtExpr->resultExpr;
726 // xxx - if this is non-unique, need to copy while making resultExpr ref
727 assertf(last->unique(), "attempt to modify weakly shared statement");
728 auto mutLast = mutate(last);
729 // above assertion means in-place mutation is OK
730 try {
731 mutLast->expr = makeCtorDtor( "?{}", ret, mutLast->expr );
732 } catch (...) {
733 std::cerr << "*CFA internal error: ";
734 std::cerr << "can't resolve implicit constructor";
735 std::cerr << " at " << stmtExpr->location.filename.c_str();
736 std::cerr << ":" << stmtExpr->location.first_line << std::endl;
737
738 abort();
739 }
740
741 // add destructors after current statement
742 stmtsToAddAfter.push_back( new ast::ExprStmt(loc, makeCtorDtor( "^?{}", ret ) ) );
743
744 // must have a non-empty body, otherwise it wouldn't have a result
745 assert( ! stmts.empty() );
746
747 // if there is a return decl, add a use as the last statement; will not have return decl on non-constructable returns
748 stmts.push_back( new ast::ExprStmt(loc, new ast::VariableExpr(loc, ret ) ) );
749
750 assert( stmtExpr->returnDecls.empty() );
751 assert( stmtExpr->dtors.empty() );
752
753 return stmtExpr;
754}
755
756// to prevent warnings ('_unq0' may be used uninitialized in this function),
757// insert an appropriate zero initializer for UniqueExpr temporaries.
758ast::Init * makeInit( const ast::Type * t, CodeLocation const & loc ) {
759 if ( auto inst = dynamic_cast< const ast::StructInstType * >( t ) ) {
760 // initizer for empty struct must be empty
761 if ( inst->base->members.empty() ) {
762 return new ast::ListInit( loc, {} );
763 }
764 } else if ( auto inst = dynamic_cast< const ast::UnionInstType * >( t ) ) {
765 // initizer for empty union must be empty
766 if ( inst->base->members.empty() ) {
767 return new ast::ListInit( loc, {} );
768 }
769 }
770
771 return new ast::ListInit( loc, {
772 new ast::SingleInit( loc, ast::ConstantExpr::from_int( loc, 0 ) )
773 } );
774}
775
776const ast::UniqueExpr * ResolveCopyCtors::previsit( const ast::UniqueExpr * unqExpr ) {
777 visit_children = false;
778 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
779 static std::unordered_map< int, const ast::UniqueExpr * > unqMap;
780 auto mutExpr = mutate(unqExpr);
781 if ( ! unqMap.count( unqExpr->id ) ) {
782 auto impCpCtorExpr = mutExpr->expr.as<ast::ImplicitCopyCtorExpr>();
783 mutExpr->expr = mutExpr->expr->accept( *visitor );
784 // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
785 assert( unqExpr->result );
786 if ( impCpCtorExpr ) {
787 auto comma = unqExpr->expr.strict_as<ast::CommaExpr>();
788 auto var = comma->arg2.strict_as<ast::VariableExpr>();
789 // note the variable used as the result from the call
790 mutExpr->var = var;
791 } else {
792 // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
793 mutExpr->object = new ast::ObjectDecl( mutExpr->location, toString("_unq", mutExpr->id), mutExpr->result, makeInit( mutExpr->result, mutExpr->location ) );
794 mutExpr->var = new ast::VariableExpr( mutExpr->location, mutExpr->object );
795 }
796
797 unqMap[mutExpr->id] = mutExpr;
798 } else {
799 // take data from other UniqueExpr to ensure consistency
800 mutExpr->expr = unqMap[mutExpr->id]->expr;
801 mutExpr->result = mutExpr->expr->result;
802 }
803 return mutExpr;
804}
805
806const ast::DeclWithType * FixInit::postvisit( const ast::ObjectDecl *_objDecl ) {
807 const CodeLocation loc = _objDecl->location;
808
809 // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postvisit)
810 ast::ptr<ast::ConstructorInit> ctorInit = _objDecl->init.as<ast::ConstructorInit>();
811
812 if ( nullptr == ctorInit ) return _objDecl;
813
814 auto objDecl = mutate(_objDecl);
815
816 // could this be non-unique?
817 if (objDecl != _objDecl) {
818 std::cerr << "FixInit: non-unique object decl " << objDecl->location << objDecl->name << std::endl;
819 }
820 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
821 assert( ! ctorInit->ctor || ! ctorInit->init );
822 if ( const ast::Stmt * ctor = ctorInit->ctor ) {
823 if ( objDecl->storage.is_static ) {
824 addDataSectionAttribute(objDecl);
825 // originally wanted to take advantage of gcc nested functions, but
826 // we get memory errors with this approach. To remedy this, the static
827 // variable is hoisted when the destructor needs to be called.
828 //
829 // generate:
830 // static T __objName_static_varN;
831 // void __objName_dtor_atexitN() {
832 // __dtor__...;
833 // }
834 // int f(...) {
835 // ...
836 // static bool __objName_uninitialized = true;
837 // if (__objName_uninitialized) {
838 // __ctor(__objName);
839 // __objName_uninitialized = false;
840 // atexit(__objName_dtor_atexitN);
841 // }
842 // ...
843 // }
844
845 static UniqueName dtorCallerNamer( "_dtor_atexit" );
846
847 // static bool __objName_uninitialized = true
848 auto boolType = new ast::BasicType( ast::BasicKind::Bool );
849 auto boolInitExpr = new ast::SingleInit(loc, ast::ConstantExpr::from_int(loc, 1 ) );
850 auto isUninitializedVar = new ast::ObjectDecl(loc, objDecl->mangleName + "_uninitialized", boolType, boolInitExpr, ast::Storage::Static, ast::Linkage::Cforall);
851 isUninitializedVar->fixUniqueId();
852
853 // __objName_uninitialized = false;
854 auto setTrue = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "?=?" ) );
855 setTrue->args.push_back( new ast::VariableExpr(loc, isUninitializedVar ) );
856 setTrue->args.push_back( ast::ConstantExpr::from_int(loc, 0 ) );
857
858 // generate body of if
859 auto initStmts = new ast::CompoundStmt(loc);
860 auto & body = initStmts->kids;
861 body.push_back( ctor );
862 body.push_back( new ast::ExprStmt(loc, setTrue ) );
863
864 // put it all together
865 auto ifStmt = new ast::IfStmt(loc, new ast::VariableExpr(loc, isUninitializedVar ), initStmts, 0 );
866 stmtsToAddAfter.push_back( new ast::DeclStmt(loc, isUninitializedVar ) );
867 stmtsToAddAfter.push_back( ifStmt );
868
869 const ast::Stmt * dtor = ctorInit->dtor;
870 if ( dtor ) {
871 // if the object has a non-trivial destructor, have to
872 // hoist it and the object into the global space and
873 // call the destructor function with atexit.
874
875 // void __objName_dtor_atexitN(...) {...}
876 ast::FunctionDecl * dtorCaller = new ast::FunctionDecl(loc, objDecl->mangleName + dtorCallerNamer.newName(), {}, {}, {}, {}, new ast::CompoundStmt(loc, {dtor}), ast::Storage::Static, ast::Linkage::C );
877 dtorCaller->fixUniqueId();
878
879 // atexit(dtor_atexit);
880 auto callAtexit = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "atexit" ) );
881 callAtexit->args.push_back( new ast::VariableExpr(loc, dtorCaller ) );
882
883 body.push_back( new ast::ExprStmt(loc, callAtexit ) );
884
885 // hoist variable and dtor caller decls to list of decls that will be added into global scope
886 staticDtorDecls.push_back( objDecl );
887 staticDtorDecls.push_back( dtorCaller );
888
889 // need to rename object uniquely since it now appears
890 // at global scope and there could be multiple function-scoped
891 // static variables with the same name in different functions.
892 // Note: it isn't sufficient to modify only the mangleName, because
893 // then subsequent SymbolTable passes can choke on seeing the object's name
894 // if another object has the same name and type. An unfortunate side-effect
895 // of renaming the object is that subsequent NameExprs may fail to resolve,
896 // but there shouldn't be any remaining past this point.
897 static UniqueName staticNamer( "_static_var" );
898 objDecl->name = objDecl->name + staticNamer.newName();
899 objDecl->mangleName = Mangle::mangle( objDecl );
900 objDecl->init = nullptr;
901
902 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
903 // create a new object which is never used
904 static UniqueName dummyNamer( "_dummy" );
905 auto dummy = new ast::ObjectDecl(loc, dummyNamer.newName(), new ast::PointerType(new ast::VoidType()), nullptr, ast::Storage::Static, ast::Linkage::Cforall, 0, { new ast::Attribute("unused") } );
906 return dummy;
907 } else {
908 objDecl->init = nullptr;
909 return objDecl;
910 }
911 } else {
912 auto implicit = strict_dynamic_cast< const ast::ImplicitCtorDtorStmt * > ( ctor );
913 auto ctorStmt = implicit->callStmt.as<ast::ExprStmt>();
914 const ast::ApplicationExpr * ctorCall = nullptr;
915 if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->expr )) && ctorCall->args.size() == 2 ) {
916 // clean up intrinsic copy constructor calls by making them into SingleInits
917 const ast::Expr * ctorArg = ctorCall->args.back();
918 // ctorCall should be gone afterwards
919 auto mutArg = mutate(ctorArg);
920 mutArg->env = ctorCall->env;
921 objDecl->init = new ast::SingleInit(loc, mutArg );
922 } else {
923 stmtsToAddAfter.push_back( ctor );
924 objDecl->init = nullptr;
925 }
926
927 const ast::Stmt * dtor = ctorInit->dtor;
928 if ( dtor ) {
929 auto implicit = strict_dynamic_cast< const ast::ImplicitCtorDtorStmt * >( dtor );
930 const ast::Stmt * dtorStmt = implicit->callStmt;
931
932 // don't need to call intrinsic dtor, because it does nothing, but
933 // non-intrinsic dtors must be called
934 if ( ! isIntrinsicSingleArgCallStmt( dtorStmt ) ) {
935 // set dtor location to the object's location for error messages
936 auto dtorFunc = getDtorFunc( objDecl, dtorStmt, stmtsToAddBefore );
937 objDecl->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr(loc, dtorFunc ) } ) );
938 } // if
939 }
940 } // if
941 } else if ( const ast::Init * init = ctorInit->init ) {
942 objDecl->init = init;
943 } else {
944 // no constructor and no initializer, which is okay
945 objDecl->init = nullptr;
946 } // if
947 return objDecl;
948}
949
950void ObjDeclCollector::previsit( const ast::CompoundStmt * ) {
951 GuardValue( curVars );
952}
953
954void ObjDeclCollector::previsit( const ast::DeclStmt * stmt ) {
955 // keep track of all variables currently in scope
956 if ( auto objDecl = stmt->decl.as<ast::ObjectDecl>() ) {
957 curVars.push_back( objDecl );
958 } // if
959}
960
961void LabelFinder::previsit( const ast::Stmt * stmt ) {
962 // for each label, remember the variables in scope at that label.
963 for ( auto l : stmt->labels ) {
964 vars[l] = curVars;
965 } // for
966}
967
968void LabelFinder::previsit( const ast::CompoundStmt * stmt ) {
969 previsit( (const ast::Stmt *)stmt );
970 Parent::previsit( stmt );
971}
972
973void LabelFinder::previsit( const ast::DeclStmt * stmt ) {
974 previsit( (const ast::Stmt *)stmt );
975 Parent::previsit( stmt );
976}
977
978void InsertDtors::previsit( const ast::FunctionDecl * funcDecl ) {
979 // each function needs to have its own set of labels
980 GuardValue( labelVars );
981 labelVars.clear();
982 // LabelFinder does not recurse into FunctionDecl, so need to visit
983 // its children manually.
984 if (funcDecl->type) funcDecl->type->accept(finder);
985 if (funcDecl->stmts) funcDecl->stmts->accept(finder);
986
987 // all labels for this function have been collected, insert destructors as appropriate via implicit recursion.
988}
989
990// Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
991// BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
992// at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
993// of the error. See C++ Reference 6.6 Jump Statements for details.
994void InsertDtors::handleGoto( const ast::BranchStmt * stmt ) {
995 // can't do anything for computed goto
996 if ( stmt->computedTarget ) return;
997
998 assertf( stmt->target.name != "", "BranchStmt missing a label: %s", toString( stmt ).c_str() );
999 // S_L = lvars = set of objects in scope at label definition
1000 // S_G = curVars = set of objects in scope at goto statement
1001 ObjectSet & lvars = labelVars[ stmt->target ];
1002
1003 DTOR_PRINT(
1004 std::cerr << "at goto label: " << stmt->target.name << std::endl;
1005 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
1006 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
1007 )
1008
1009
1010 // std::set_difference requires that the inputs be sorted.
1011 lvars.sort();
1012 curVars.sort();
1013
1014 ObjectSet diff;
1015 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
1016 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
1017 DTOR_PRINT(
1018 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
1019 )
1020 if ( ! diff.empty() ) {
1021 SemanticError( stmt->location, "jump to label \"%s\" crosses initialization of \"%s\".",
1022 stmt->target.name.c_str(), (*diff.begin())->name.c_str() );
1023 } // if
1024}
1025
1026void InsertDtors::previsit( const ast::BranchStmt * stmt ) {
1027 switch( stmt->kind ) {
1028 case ast::BranchStmt::Continue:
1029 case ast::BranchStmt::Break:
1030 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
1031 // always be empty), but it serves as a small sanity check.
1032 case ast::BranchStmt::Goto:
1033 handleGoto( stmt );
1034 break;
1035 default:
1036 assert( false );
1037 } // switch
1038}
1039
1040/// Should we check for warnings? (The function is user-defined constrctor or destructor.)
1041bool checkWarnings( const ast::FunctionDecl * funcDecl ) {
1042 if ( ! funcDecl ) return false;
1043 if ( ! funcDecl->stmts ) return false;
1044 return CodeGen::isCtorDtor( funcDecl->name ) && ! funcDecl->linkage.is_overrideable;
1045}
1046
1047void GenStructMemberCalls::previsit( const ast::FunctionDecl * funcDecl ) {
1048 GuardValue( function );
1049 GuardValue( unhandled );
1050 GuardValue( usedUninit );
1051 GuardValue( thisParam );
1052 GuardValue( isCtor );
1053 GuardValue( structDecl );
1054 errors = SemanticErrorException(); // clear previous errors
1055
1056 // need to start with fresh sets
1057 unhandled.clear();
1058 usedUninit.clear();
1059
1060 function = mutate(funcDecl);
1061 // could this be non-unique?
1062 if (function != funcDecl) {
1063 std::cerr << "GenStructMemberCalls: non-unique FunctionDecl " << funcDecl->location << funcDecl->name << std::endl;
1064 }
1065
1066 isCtor = CodeGen::isConstructor( function->name );
1067
1068 // Remaining code is only for warnings.
1069 if ( ! checkWarnings( function ) ) return;
1070 thisParam = function->params.front().strict_as<ast::ObjectDecl>();
1071 auto thisType = getPointerBase( thisParam->get_type() );
1072 auto structType = dynamic_cast< const ast::StructInstType * >( thisType );
1073 if ( structType ) {
1074 structDecl = structType->base;
1075 for ( auto & member : structDecl->members ) {
1076 if ( auto field = member.as<ast::ObjectDecl>() ) {
1077 // record all of the struct type's members that need to be constructed or
1078 // destructed by the end of the function
1079 unhandled.insert( field );
1080 }
1081 }
1082 }
1083}
1084
1085const ast::DeclWithType * GenStructMemberCalls::postvisit( const ast::FunctionDecl * funcDecl ) {
1086 // remove the unhandled objects from usedUninit, because a call is inserted
1087 // to handle them - only objects that are later constructed are used uninitialized.
1088 std::map< const ast::DeclWithType *, CodeLocation > diff;
1089 // need the comparator since usedUninit and unhandled have different types
1090 struct comp_t {
1091 typedef decltype(usedUninit)::value_type usedUninit_t;
1092 typedef decltype(unhandled)::value_type unhandled_t;
1093 bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
1094 bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
1095 } comp;
1096 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
1097 for ( auto p : diff ) {
1098 auto member = p.first;
1099 auto loc = p.second;
1100 // xxx - make error message better by also tracking the location that the object is constructed at?
1101 emit( loc, "in ", function->name, ", field ", member->name, " used before being constructed" );
1102 }
1103
1104 const CodeLocation loc = funcDecl->location;
1105
1106 if ( ! unhandled.empty() ) {
1107 auto mutStmts = function->stmts.get_and_mutate();
1108 // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
1109 auto guard = makeFuncGuard( [this]() { symtab.enterScope(); }, [this]() { symtab.leaveScope(); } );
1110 symtab.addFunction( function );
1111 auto global = transUnit().global;
1112
1113 // need to iterate through members in reverse in order for
1114 // ctor/dtor statements to come out in the right order
1115 for ( auto & member : reverseIterate( structDecl->members ) ) {
1116 auto field = member.as<ast::ObjectDecl>();
1117 // skip non-DWT members
1118 if ( ! field ) continue;
1119 // skip non-constructable members
1120 if ( ! tryConstruct( field ) ) continue;
1121 // skip handled members
1122 if ( ! unhandled.count( field ) ) continue;
1123
1124 // insert and resolve default/copy constructor call for each field that's unhandled
1125 ast::Expr * arg2 = nullptr;
1126 if ( function->name == "?{}" && isCopyFunction( function ) ) {
1127 // if copy ctor, need to pass second-param-of-this-function.field
1128 assert( function->params.size() == 2 );
1129 arg2 = new ast::MemberExpr(funcDecl->location, field, new ast::VariableExpr(funcDecl->location, function->params.back() ) );
1130 }
1131 InitExpander srcParam( arg2 );
1132 // cast away reference type and construct field.
1133 ast::Expr * thisExpr = new ast::CastExpr(funcDecl->location, new ast::VariableExpr(funcDecl->location, thisParam ), thisParam->get_type()->stripReferences());
1134 ast::Expr * memberDest = new ast::MemberExpr(funcDecl->location, field, thisExpr );
1135 const ast::Stmt * callStmt = SymTab::genImplicitCall( srcParam, memberDest, loc, function->name, field, static_cast<SymTab::LoopDirection>(isCtor) );
1136
1137 if ( callStmt ) {
1138 try {
1139 callStmt = callStmt->accept( *visitor );
1140 if ( isCtor ) {
1141 mutStmts->push_front( callStmt );
1142 } else { // TODO: don't generate destructor function/object for intrinsic calls
1143
1144 // Optimization: do not need to call intrinsic destructors on members
1145 if ( isIntrinsicSingleArgCallStmt( callStmt ) ) continue;
1146
1147 // __Destructor _dtor0 = { (void *)&b.a1, (void (*)(void *)_destroy_A };
1148 std::list< ast::ptr<ast::Stmt> > stmtsToAdd;
1149
1150 static UniqueName memberDtorNamer = { "__memberDtor" };
1151 assertf( global.dtorStruct, "builtin __Destructor not found." );
1152 assertf( global.dtorDestroy, "builtin __destroy_Destructor not found." );
1153
1154 ast::Expr * thisExpr = new ast::CastExpr( new ast::AddressExpr( new ast::VariableExpr(loc, thisParam ) ), new ast::PointerType( new ast::VoidType(), ast::CV::Qualifiers() ) );
1155 ast::Expr * dtorExpr = new ast::VariableExpr(loc, getDtorFunc( thisParam, callStmt, stmtsToAdd ) );
1156
1157 // cast destructor pointer to void (*)(void *), to silence GCC incompatible pointer warnings
1158 auto dtorFtype = new ast::FunctionType();
1159 dtorFtype->params.emplace_back( new ast::PointerType( new ast::VoidType() ) );
1160 auto dtorType = new ast::PointerType( dtorFtype );
1161
1162 auto destructor = new ast::ObjectDecl(loc, memberDtorNamer.newName(), new ast::StructInstType( global.dtorStruct ), new ast::ListInit(loc, { new ast::SingleInit(loc, thisExpr ), new ast::SingleInit(loc, new ast::CastExpr( dtorExpr, dtorType ) ) } ) );
1163 destructor->attributes.push_back( new ast::Attribute( "cleanup", { new ast::VariableExpr( loc, global.dtorDestroy ) } ) );
1164 mutStmts->push_front( new ast::DeclStmt(loc, destructor ) );
1165 mutStmts->kids.splice( mutStmts->kids.begin(), stmtsToAdd );
1166 }
1167 } catch ( SemanticErrorException & error ) {
1168 emit( funcDecl->location, "in ", function->name , ", field ", field->name, " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
1169 }
1170 }
1171 }
1172 function->stmts = mutStmts;
1173 }
1174 errors.throwIfNonEmpty();
1175 return function;
1176}
1177
1178/// true if expr is effectively just the 'this' parameter
1179bool isThisExpression( const ast::Expr * expr, const ast::DeclWithType * thisParam ) {
1180 // TODO: there are more complicated ways to pass 'this' to a constructor, e.g. &*, *&, etc.
1181 if ( auto varExpr = dynamic_cast< const ast::VariableExpr * >( expr ) ) {
1182 return varExpr->var == thisParam;
1183 } else if ( auto castExpr = dynamic_cast< const ast::CastExpr * > ( expr ) ) {
1184 return isThisExpression( castExpr->arg, thisParam );
1185 }
1186 return false;
1187}
1188
1189/// returns a MemberExpr if expr is effectively just member access on the 'this' parameter, else nullptr
1190const ast::MemberExpr * isThisMemberExpr( const ast::Expr * expr, const ast::DeclWithType * thisParam ) {
1191 if ( auto memberExpr = dynamic_cast< const ast::MemberExpr * >( expr ) ) {
1192 if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
1193 return memberExpr;
1194 }
1195 } else if ( auto castExpr = dynamic_cast< const ast::CastExpr * >( expr ) ) {
1196 return isThisMemberExpr( castExpr->arg, thisParam );
1197 }
1198 return nullptr;
1199}
1200
1201void GenStructMemberCalls::previsit( const ast::ApplicationExpr * appExpr ) {
1202 if ( ! checkWarnings( function ) ) {
1203 visit_children = false;
1204 return;
1205 }
1206
1207 std::string fname = getFunctionName( appExpr );
1208 if ( fname != function->name ) return;
1209
1210 // call to same kind of function
1211 const ast::Expr * firstParam = appExpr->args.front();
1212 if ( isThisExpression( firstParam, thisParam ) ) {
1213 // if calling another constructor on thisParam, assume that function handles
1214 // all members - if it doesn't a warning will appear in that function.
1215 unhandled.clear();
1216 } else if ( auto memberExpr = isThisMemberExpr( firstParam, thisParam ) ) {
1217 // if first parameter is a member expression on the this parameter,
1218 // then remove the member from unhandled set.
1219 if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
1220 unhandled.erase( memberExpr->member );
1221 }
1222 }
1223}
1224
1225void GenStructMemberCalls::previsit( const ast::MemberExpr * memberExpr ) {
1226 if ( ! checkWarnings( function ) || ! isCtor ) {
1227 visit_children = false;
1228 return;
1229 }
1230
1231 if ( isThisExpression( memberExpr->aggregate, thisParam ) ) {
1232 if ( unhandled.count( memberExpr->member ) ) {
1233 // emit a warning because a member was used before it was constructed
1234 usedUninit.insert( { memberExpr->member, memberExpr->location } );
1235 }
1236 }
1237}
1238
1239template< typename... Params >
1240void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
1241 SemanticErrorException err( loc, toString( params... ) );
1242 errors.append( err );
1243}
1244
1245const ast::Expr * GenStructMemberCalls::postvisit( const ast::UntypedExpr * untypedExpr ) {
1246 // xxx - functions returning ast::ptr seems wrong...
1247 auto res = ResolvExpr::findVoidExpression( untypedExpr, { symtab, transUnit().global } );
1248 return res.release();
1249}
1250
1251void InsertImplicitCalls::previsit(const ast::UniqueExpr * unqExpr) {
1252 if (visitedIds.count(unqExpr->id)) visit_children = false;
1253 else visitedIds.insert(unqExpr->id);
1254}
1255
1256const ast::Expr * FixCtorExprs::postvisit( const ast::ConstructorExpr * ctorExpr ) {
1257 const CodeLocation loc = ctorExpr->location;
1258 static UniqueName tempNamer( "_tmp_ctor_expr" );
1259 // xxx - is the size check necessary?
1260 assert( ctorExpr->result && ctorExpr->result->size() == 1 );
1261
1262 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1263 // take possession of expr and env
1264 ast::ptr<ast::ApplicationExpr> callExpr = ctorExpr->callExpr.strict_as<ast::ApplicationExpr>();
1265 ast::ptr<ast::TypeSubstitution> env = ctorExpr->env;
1266
1267 // xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary.
1268 auto tmp = new ast::ObjectDecl(loc, tempNamer.newName(), callExpr->args.front()->result );
1269 declsToAddBefore.push_back( tmp );
1270
1271 // build assignment and replace constructor's first argument with new temporary
1272 auto mutCallExpr = callExpr.get_and_mutate();
1273 const ast::Expr * firstArg = callExpr->args.front();
1274 ast::Expr * assign = new ast::UntypedExpr(loc, new ast::NameExpr(loc, "?=?" ), { new ast::AddressExpr(loc, new ast::VariableExpr(loc, tmp ) ), new ast::AddressExpr( firstArg ) } );
1275 firstArg = new ast::VariableExpr(loc, tmp );
1276 mutCallExpr->args.front() = firstArg;
1277
1278 // resolve assignment and dispose of new env
1279 auto resolved = ResolvExpr::findVoidExpression( assign, { symtab, transUnit().global } );
1280 auto mut = resolved.get_and_mutate();
1281 assertf(resolved.get() == mut, "newly resolved expression must be unique");
1282 mut->env = nullptr;
1283
1284 // for constructor expr:
1285 // T x;
1286 // x{};
1287 // results in:
1288 // T x;
1289 // T & tmp;
1290 // &tmp = &x, ?{}(tmp), tmp
1291 ast::CommaExpr * commaExpr = new ast::CommaExpr(loc, resolved, new ast::CommaExpr(loc, mutCallExpr, new ast::VariableExpr(loc, tmp ) ) );
1292 commaExpr->env = env;
1293 return commaExpr;
1294}
1295
1296} // namespace
1297
1298void fix( ast::TranslationUnit & translationUnit, bool inLibrary ) {
1299 ast::Pass<SelfAssignChecker>::run( translationUnit );
1300
1301 // fixes StmtExpr to properly link to their resulting expression
1302 ast::Pass<StmtExprResult>::run( translationUnit );
1303
1304 // fixes ConstructorInit for global variables. should happen before fixInitializers.
1305 InitTweak::fixGlobalInit( translationUnit, inLibrary );
1306
1307 // must happen before ResolveCopyCtors because temporaries have to be inserted into the correct scope
1308 ast::Pass<SplitExpressions>::run( translationUnit );
1309
1310 ast::Pass<InsertImplicitCalls>::run( translationUnit );
1311
1312 // Needs to happen before ResolveCopyCtors, because argument/return temporaries should not be considered in
1313 // error checking branch statements
1314 {
1315 ast::Pass<LabelFinder> finder;
1316 ast::Pass<InsertDtors>::run( translationUnit, finder );
1317 }
1318
1319 ast::Pass<ResolveCopyCtors>::run( translationUnit );
1320 FixInit::fixInitializers( translationUnit );
1321 ast::Pass<GenStructMemberCalls>::run( translationUnit );
1322
1323 // Needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
1324 // don't have the correct form, and a member can be constructed more than once.
1325 ast::Pass<FixCtorExprs>::run( translationUnit );
1326}
1327
1328} // namespace InitTweak
1329
1330// Local Variables: //
1331// tab-width: 4 //
1332// mode: c++ //
1333// compile-command: "make install" //
1334// End: //
Note: See TracBrowser for help on using the repository browser.