source: src/InitTweak/FixInit.cc@ 62e5546

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 62e5546 was 62e5546, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

Removed warnings when compiling with clang

  • Property mode set to 100644
File size: 42.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// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jul 12 17:41:15 2016
13// Update Count : 34
14//
15
16#include <stack>
17#include <list>
18#include <iterator>
19#include <algorithm>
20#include "InitTweak.h"
21#include "FixInit.h"
22#include "FixGlobalInit.h"
23#include "ResolvExpr/Resolver.h"
24#include "ResolvExpr/typeops.h"
25#include "SynTree/Declaration.h"
26#include "SynTree/Type.h"
27#include "SynTree/Expression.h"
28#include "SynTree/Attribute.h"
29#include "SynTree/Statement.h"
30#include "SynTree/Initializer.h"
31#include "SynTree/Mutator.h"
32#include "SymTab/Indexer.h"
33#include "SymTab/Autogen.h"
34#include "GenPoly/PolyMutator.h"
35#include "GenPoly/DeclMutator.h"
36#include "SynTree/AddStmtVisitor.h"
37#include "CodeGen/GenType.h" // for warnings
38
39bool ctordtorp = false;
40bool ctorp = false;
41bool cpctorp = false;
42bool dtorp = false;
43#define PRINT( text ) if ( ctordtorp ) { text }
44#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
45#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
46
47namespace InitTweak {
48 namespace {
49 const std::list<Label> noLabels;
50 const std::list<Expression*> noDesignators;
51
52 class InsertImplicitCalls final : public GenPoly::PolyMutator {
53 public:
54 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
55 /// function calls need their parameters to be copy constructed
56 static void insert( std::list< Declaration * > & translationUnit );
57
58 using GenPoly::PolyMutator::mutate;
59 virtual Expression * mutate( ApplicationExpr * appExpr ) override;
60 };
61
62 class ResolveCopyCtors final : public SymTab::Indexer {
63 public:
64 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
65 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
66 /// arguments and return value temporaries
67 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
68
69 using SymTab::Indexer::visit;
70 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
71
72 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
73 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
74 /// true if type does not need to be copy constructed to ensure correctness
75 bool skipCopyConstruct( Type * );
76 private:
77 TypeSubstitution * env;
78 };
79
80 /// collects constructed object decls - used as a base class
81 class ObjDeclCollector : public AddStmtVisitor {
82 public:
83 typedef AddStmtVisitor Parent;
84 using Parent::visit;
85 typedef std::set< ObjectDecl * > ObjectSet;
86 virtual void visit( CompoundStmt *compoundStmt ) override;
87 virtual void visit( DeclStmt *stmt ) override;
88 protected:
89 ObjectSet curVars;
90 };
91
92 // debug
93 struct printSet {
94 typedef ObjDeclCollector::ObjectSet ObjectSet;
95 printSet( const ObjectSet & objs ) : objs( objs ) {}
96 const ObjectSet & objs;
97 };
98 std::ostream & operator<<( std::ostream & out, const printSet & set) {
99 out << "{ ";
100 for ( ObjectDecl * obj : set.objs ) {
101 out << obj->get_name() << ", " ;
102 } // for
103 out << " }";
104 return out;
105 }
106
107 class LabelFinder final : public ObjDeclCollector {
108 public:
109 typedef ObjDeclCollector Parent;
110 typedef std::map< Label, ObjectSet > LabelMap;
111 // map of Label -> live variables at that label
112 LabelMap vars;
113
114 void handleStmt( Statement * stmt );
115
116 // xxx - This needs to be done better.
117 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
118 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
119 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
120 // every specialized class knows about every new kind of statement that might be added.
121 using Parent::visit;
122 virtual void visit( CompoundStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
123 virtual void visit( ExprStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
124 virtual void visit( AsmStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
125 virtual void visit( IfStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
126 virtual void visit( WhileStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
127 virtual void visit( ForStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
128 virtual void visit( SwitchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
129 virtual void visit( CaseStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
130 virtual void visit( BranchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
131 virtual void visit( ReturnStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
132 virtual void visit( TryStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
133 virtual void visit( CatchStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
134 virtual void visit( FinallyStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
135 virtual void visit( NullStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
136 virtual void visit( DeclStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
137 virtual void visit( ImplicitCtorDtorStmt *stmt ) override { handleStmt( stmt ); return Parent::visit( stmt ); }
138 };
139
140 class InsertDtors final : public ObjDeclCollector {
141 public:
142 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
143 /// (currently by FixInit)
144 static void insert( std::list< Declaration * > & translationUnit );
145
146 typedef ObjDeclCollector Parent;
147 typedef std::list< ObjectDecl * > OrderedDecls;
148 typedef std::list< OrderedDecls > OrderedDeclsStack;
149
150 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
151
152 using Parent::visit;
153
154 virtual void visit( ObjectDecl * objDecl ) override;
155
156 virtual void visit( CompoundStmt * compoundStmt ) override;
157 virtual void visit( ReturnStmt * returnStmt ) override;
158 virtual void visit( BranchStmt * stmt ) override;
159 private:
160 void handleGoto( BranchStmt * stmt );
161
162 LabelFinder::LabelMap & labelVars;
163 OrderedDeclsStack reverseDeclOrder;
164 };
165
166 class FixInit final : public GenPoly::PolyMutator {
167 public:
168 /// expand each object declaration to use its constructor after it is declared.
169 static void fixInitializers( std::list< Declaration * > &translationUnit );
170
171 using GenPoly::PolyMutator::mutate;
172 virtual DeclarationWithType * mutate( ObjectDecl *objDecl ) override;
173
174 std::list< Declaration * > staticDtorDecls;
175 };
176
177 class FixCopyCtors final : public GenPoly::PolyMutator {
178 public:
179 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
180 /// and destructors
181 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
182
183 using GenPoly::PolyMutator::mutate;
184 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) override;
185 };
186
187 class GenStructMemberCalls final : public SymTab::Indexer {
188 public:
189 typedef Indexer Parent;
190 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
191 /// for any member that is missing a corresponding ctor/dtor call.
192 /// error if a member is used before constructed
193 static void generate( std::list< Declaration * > & translationUnit );
194
195 using Parent::visit;
196
197 virtual void visit( FunctionDecl * funcDecl ) override;
198
199 virtual void visit( MemberExpr * memberExpr ) override;
200 virtual void visit( ApplicationExpr * appExpr ) override;
201
202 SemanticError errors;
203 private:
204 void handleFirstParam( Expression * firstParam );
205 template< typename... Params >
206 void emit( const Params &... params );
207
208 FunctionDecl * function = 0;
209 std::set< DeclarationWithType * > unhandled, usedUninit;
210 ObjectDecl * thisParam = 0;
211 bool isCtor = false; // true if current function is a constructor
212 StructDecl * structDecl = 0;
213 };
214
215 // very simple resolver-like mutator class - used to
216 // resolve UntypedExprs that are found within newly
217 // generated constructor/destructor calls
218 class MutatingResolver final : public Mutator {
219 public:
220 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
221
222 using Mutator::mutate;
223 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
224 virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
225
226 private:
227 SymTab::Indexer & indexer;
228 };
229
230 class FixCtorExprs final : public GenPoly::DeclMutator {
231 public:
232 /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
233 static void fix( std::list< Declaration * > & translationUnit );
234
235 using GenPoly::DeclMutator::mutate;
236 virtual Expression * mutate( ConstructorExpr * ctorExpr ) override;
237 };
238 } // namespace
239
240 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
241 // fixes ConstructorInit for global variables. should happen before fixInitializers.
242 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
243
244
245 InsertImplicitCalls::insert( translationUnit );
246 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
247 InsertDtors::insert( translationUnit );
248 FixInit::fixInitializers( translationUnit );
249
250 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
251 FixCopyCtors::fixCopyCtors( translationUnit );
252
253 GenStructMemberCalls::generate( translationUnit );
254 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
255 // hack in the way untyped assignments are generated, where the first argument cannot have
256 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
257 // Thus such assignment exprs must never pushed through expression resolution (and thus should
258 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
259 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
260 // don't look right, and a member can be constructed more than once.
261 FixCtorExprs::fix( translationUnit );
262 }
263
264 namespace {
265 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
266 InsertImplicitCalls inserter;
267 mutateAll( translationUnit, inserter );
268 }
269
270 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
271 ResolveCopyCtors resolver;
272 acceptAll( translationUnit, resolver );
273 }
274
275 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
276 FixInit fixer;
277
278 // can't use mutateAll, because need to insert declarations at top-level
279 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
280 SemanticError errors;
281 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
282 try {
283 *i = maybeMutate( *i, fixer );
284 translationUnit.splice( i, fixer.staticDtorDecls );
285 } catch( SemanticError &e ) {
286 errors.append( e );
287 } // try
288 } // for
289 if ( ! errors.isEmpty() ) {
290 throw errors;
291 } // if
292 }
293
294 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
295 LabelFinder finder;
296 InsertDtors inserter( finder );
297 acceptAll( translationUnit, finder );
298 acceptAll( translationUnit, inserter );
299 }
300
301 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
302 FixCopyCtors fixer;
303 mutateAll( translationUnit, fixer );
304 }
305
306 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
307 GenStructMemberCalls warner;
308 acceptAll( translationUnit, warner );
309
310 // visitor doesn't throw so that it can collect all errors
311 if ( ! warner.errors.isEmpty() ) {
312 throw warner.errors;
313 }
314 }
315
316 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
317 FixCtorExprs fixer;
318 fixer.mutateDeclarationList( translationUnit );
319 }
320
321 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
322 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
323 assert( appExpr );
324
325 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
326 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
327 // optimization: don't need to copy construct in order to call intrinsic functions
328 return appExpr;
329 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
330 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
331 assert( ftype );
332 if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
333 Type * t1 = ftype->get_parameters().front()->get_type();
334 Type * t2 = ftype->get_parameters().back()->get_type();
335 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
336 assert( ptrType );
337
338 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
339 // optimization: don't need to copy construct in order to call a copy constructor or
340 // assignment operator
341 return appExpr;
342 } // if
343 } else if ( isDestructor( funcDecl->get_name() ) ) {
344 // correctness: never copy construct arguments to a destructor
345 return appExpr;
346 } // if
347 } // if
348 } // if
349 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
350
351 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
352 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
353 // save the type substitution onto the new node so that it is easy to find.
354 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
355 // The substitution is needed to obtain the type of temporary variables so that copy constructor
356 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
357 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
358 // saves the environment, or compute the types of temporaries here, but it's much simpler to
359 // save the environment here, and more cohesive to compute temporary variables and resolve copy
360 // constructor calls together.
361 assert( env );
362 expr->set_env( env );
363 return expr;
364 }
365
366 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
367 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
368 }
369
370 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
371 assert( var );
372 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
373 untyped->get_args().push_back( new AddressExpr( new VariableExpr( var ) ) );
374 if (cpArg) untyped->get_args().push_back( cpArg->clone() );
375
376 // resolve copy constructor
377 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
378 // (VariableExpr and already resolved expression)
379 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
380 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
381 if ( resolved->get_env() ) {
382 env->add( *resolved->get_env() );
383 } // if
384
385 assert( resolved );
386 delete untyped;
387 return resolved;
388 }
389
390 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
391 static UniqueName tempNamer("_tmp_cp");
392 static UniqueName retNamer("_tmp_cp_ret");
393
394 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
395 Visitor::visit( impCpCtorExpr );
396 env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
397
398 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
399
400 // take each argument and attempt to copy construct it.
401 for ( Expression * & arg : appExpr->get_args() ) {
402 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
403 // xxx - need to handle tuple arguments
404 assert( ! arg->get_results().empty() );
405 Type * result = arg->get_results().front();
406 if ( skipCopyConstruct( result ) ) continue; // skip certain non-copyable types
407 // type may involve type variables, so apply type substitution to get temporary variable's actual type
408 result = result->clone();
409 impCpCtorExpr->get_env()->apply( result );
410 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
411 tmp->get_type()->set_isConst( false );
412
413 // create and resolve copy constructor
414 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
415 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
416
417 // if the chosen constructor is intrinsic, the copy is unnecessary, so
418 // don't create the temporary and don't call the copy constructor
419 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
420 assert( function );
421 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
422 // replace argument to function call with temporary
423 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
424 impCpCtorExpr->get_tempDecls().push_back( tmp );
425 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
426 } // if
427 } // for
428
429 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
430 // initialized with the return value and is destructed later
431 // xxx - handle multiple return values
432 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
433 // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
434 // level. Trying to pass that environment along.
435 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
436 for ( Type * result : appExpr->get_results() ) {
437 result = result->clone();
438 impCpCtorExpr->get_env()->apply( result );
439 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
440 ret->get_type()->set_isConst( false );
441 impCpCtorExpr->get_returnDecls().push_back( ret );
442 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
443 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
444 } // for
445 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
446 }
447
448
449 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
450 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
451
452 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
453 assert( impCpCtorExpr );
454
455 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
456 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
457 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
458
459 // add all temporary declarations and their constructors
460 for ( ObjectDecl * obj : tempDecls ) {
461 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
462 } // for
463 for ( ObjectDecl * obj : returnDecls ) {
464 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
465 } // for
466
467 // add destructors after current statement
468 for ( Expression * dtor : dtors ) {
469 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
470 } // for
471
472 // xxx - update to work with multiple return values
473 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
474 Expression * callExpr = impCpCtorExpr->get_callExpr();
475
476 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
477
478 // detach fields from wrapper node so that it can be deleted without deleting too much
479 dtors.clear();
480 tempDecls.clear();
481 returnDecls.clear();
482 impCpCtorExpr->set_callExpr( NULL );
483 impCpCtorExpr->set_env( NULL );
484 delete impCpCtorExpr;
485
486 if ( returnDecl ) {
487 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
488 assign->get_args().push_back( new VariableExpr( returnDecl ) );
489 assign->get_args().push_back( callExpr );
490 // know the result type of the assignment is the type of the LHS (minus the pointer), so
491 // add that onto the assignment expression so that later steps have the necessary information
492 assign->add_result( returnDecl->get_type()->clone() );
493
494 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
495 if ( callExpr->get_results().front()->get_isLvalue() ) {
496 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
497 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
498 // type of the return temporary from T to T* to properly capture the return value. Then dereference
499 // the result of the comma expression, since the lvalue returning call was originally wrapped with
500 // an AddressExpr. Effectively, this turns
501 // lvalue T f();
502 // &*f()
503 // into
504 // T * tmp_cp_retN;
505 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
506 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
507 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
508
509 Type * resultType = returnDecl->get_type()->clone();
510 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
511 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
512 deref->get_args().push_back( retExpr );
513 deref->add_result( resultType );
514 retExpr = deref;
515 } // if
516 retExpr->set_env( env->clone() );
517 return retExpr;
518 } else {
519 return callExpr;
520 } // if
521 }
522
523 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
524 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
525 // is removed from the ObjectDecl
526 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
527
528 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
529 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
530 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
531 if ( Statement * ctor = ctorInit->get_ctor() ) {
532 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
533 // originally wanted to take advantage of gcc nested functions, but
534 // we get memory errors with this approach. To remedy this, the static
535 // variable is hoisted when the destructor needs to be called.
536 //
537 // generate:
538 // static T __objName_static_varN;
539 // void __objName_dtor_atexitN() {
540 // __dtor__...;
541 // }
542 // int f(...) {
543 // ...
544 // static bool __objName_uninitialized = true;
545 // if (__objName_uninitialized) {
546 // __ctor(__objName);
547 // __objName_uninitialized = false;
548 // atexit(__objName_dtor_atexitN);
549 // }
550 // ...
551 // }
552
553 static UniqueName dtorCallerNamer( "_dtor_atexit" );
554
555 // static bool __objName_uninitialized = true
556 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
557 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
558 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
559 isUninitializedVar->fixUniqueId();
560
561 // __objName_uninitialized = false;
562 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
563 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
564 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
565
566 // generate body of if
567 CompoundStmt * initStmts = new CompoundStmt( noLabels );
568 std::list< Statement * > & body = initStmts->get_kids();
569 body.push_back( ctor );
570 body.push_back( new ExprStmt( noLabels, setTrue ) );
571
572 // put it all together
573 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
574 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
575 stmtsToAddAfter.push_back( ifStmt );
576
577 if ( ctorInit->get_dtor() ) {
578 // if the object has a non-trivial destructor, have to
579 // hoist it and the object into the global space and
580 // call the destructor function with atexit.
581
582 Statement * dtorStmt = ctorInit->get_dtor()->clone();
583
584 // void __objName_dtor_atexitN(...) {...}
585 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
586 dtorCaller->fixUniqueId();
587 dtorCaller->get_statements()->push_back( dtorStmt );
588
589 // atexit(dtor_atexit);
590 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
591 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
592
593 body.push_back( new ExprStmt( noLabels, callAtexit ) );
594
595 // hoist variable and dtor caller decls to list of decls that will be added into global scope
596 staticDtorDecls.push_back( objDecl );
597 staticDtorDecls.push_back( dtorCaller );
598
599 // need to rename object uniquely since it now appears
600 // at global scope and there could be multiple function-scoped
601 // static variables with the same name in different functions.
602 // Note: it isn't sufficient to modify only the mangleName, because
603 // then subsequent Indexer passes can choke on seeing the object's name
604 // if another object has the same name and type. An unfortunate side-effect
605 // of renaming the object is that subsequent NameExprs may fail to resolve,
606 // but there shouldn't be any remaining past this point.
607 static UniqueName staticNamer( "_static_var" );
608 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
609 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
610
611 objDecl->set_init( NULL );
612 ctorInit->set_ctor( NULL );
613 delete ctorInit;
614
615 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
616 // create a new object which is never used
617 static UniqueName dummyNamer( "_dummy" );
618 ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
619 return dummy;
620 }
621 } else {
622 stmtsToAddAfter.push_back( ctor );
623 } // if
624 objDecl->set_init( NULL );
625 ctorInit->set_ctor( NULL );
626 } else if ( Initializer * init = ctorInit->get_init() ) {
627 objDecl->set_init( init );
628 ctorInit->set_init( NULL );
629 } else {
630 // no constructor and no initializer, which is okay
631 objDecl->set_init( NULL );
632 } // if
633 delete ctorInit;
634 } // if
635 return objDecl;
636 }
637
638 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
639 std::set< ObjectDecl * > prevVars = curVars;
640 Parent::visit( compoundStmt );
641 curVars = prevVars;
642 }
643
644 void ObjDeclCollector::visit( DeclStmt *stmt ) {
645 // keep track of all variables currently in scope
646 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
647 curVars.insert( objDecl );
648 } // if
649 Parent::visit( stmt );
650 }
651
652 void LabelFinder::handleStmt( Statement * stmt ) {
653 // for each label, remember the variables in scope at that label.
654 for ( Label l : stmt->get_labels() ) {
655 vars[l] = curVars;
656 } // for
657 }
658
659 template<typename Iterator, typename OutputIterator>
660 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
661 for ( Iterator it = begin ; it != end ; ++it ) {
662 // extract destructor statement from the object decl and insert it into the output. Note that this is
663 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
664 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
665 // contain side effects.
666 ObjectDecl * objDecl = *it;
667 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
668 assert( ctorInit && ctorInit->get_dtor() );
669 *out++ = ctorInit->get_dtor()->clone();
670 } // for
671 }
672
673 void InsertDtors::visit( ObjectDecl * objDecl ) {
674 // remember non-static destructed objects so that their destructors can be inserted later
675 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
676 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
677 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
678 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
679 Statement * dtor = ctorInit->get_dtor();
680 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
681 // don't need to call intrinsic dtor, because it does nothing, but
682 // non-intrinsic dtors must be called
683 reverseDeclOrder.front().push_front( objDecl );
684 } // if
685 } // if
686 } // if
687 Parent::visit( objDecl );
688 }
689
690 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
691 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
692 // when block is left, just the destructors associated with variables defined in this block, so push a new
693 // list to the top of the stack so that we can differentiate scopes
694 reverseDeclOrder.push_front( OrderedDecls() );
695 Parent::visit( compoundStmt );
696
697 // add destructors for the current scope that we're exiting
698 std::list< Statement * > & statements = compoundStmt->get_kids();
699 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
700 reverseDeclOrder.pop_front();
701 }
702
703 void InsertDtors::visit( ReturnStmt * returnStmt ) {
704 // return exits all scopes, so dump destructors for all scopes
705 for ( OrderedDecls & od : reverseDeclOrder ) {
706 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
707 } // for
708 }
709
710 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
711 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
712 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
713 // of the error. See C++ Reference 6.6 Jump Statements for details.
714 void InsertDtors::handleGoto( BranchStmt * stmt ) {
715 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
716 // S_L = lvars = set of objects in scope at label definition
717 // S_G = curVars = set of objects in scope at goto statement
718 ObjectSet & lvars = labelVars[ stmt->get_target() ];
719
720 DTOR_PRINT(
721 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
722 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
723 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
724 )
725
726 ObjectSet diff;
727 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
728 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
729 DTOR_PRINT(
730 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
731 )
732 if ( ! diff.empty() ) {
733 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
734 } // if
735 // S_G-S_L results in set of objects that must be destructed
736 diff.clear();
737 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
738 DTOR_PRINT(
739 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
740 )
741 if ( ! diff.empty() ) {
742 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
743 OrderedDecls ordered;
744 for ( OrderedDecls & rdo : reverseDeclOrder ) {
745 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
746 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
747 } // for
748 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
749 } // if
750 }
751
752 void InsertDtors::visit( BranchStmt * stmt ) {
753 switch( stmt->get_type() ) {
754 case BranchStmt::Continue:
755 case BranchStmt::Break:
756 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
757 // always be empty), but it serves as a small sanity check.
758 case BranchStmt::Goto:
759 handleGoto( stmt );
760 break;
761 default:
762 assert( false );
763 } // switch
764 }
765
766 bool checkWarnings( FunctionDecl * funcDecl ) {
767 // only check for warnings if the current function is a user-defined
768 // constructor or destructor
769 if ( ! funcDecl ) return false;
770 if ( ! funcDecl->get_statements() ) return false;
771 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
772 }
773
774 void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
775 ValueGuard< FunctionDecl * > oldFunction( funcDecl );
776 ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
777 ValueGuard< std::set< DeclarationWithType * > > oldUsedUninit( usedUninit );
778 ValueGuard< ObjectDecl * > oldThisParam( thisParam );
779 ValueGuard< bool > oldIsCtor( isCtor );
780 ValueGuard< StructDecl * > oldStructDecl( structDecl );
781
782 // need to start with fresh sets
783 unhandled.clear();
784 usedUninit.clear();
785
786 function = funcDecl;
787 isCtor = isConstructor( function->get_name() );
788 if ( checkWarnings( function ) ) {
789 FunctionType * type = function->get_functionType();
790 assert( ! type->get_parameters().empty() );
791 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
792 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
793 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
794 if ( structType ) {
795 structDecl = structType->get_baseStruct();
796 for ( Declaration * member : structDecl->get_members() ) {
797 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
798 // record all of the struct type's members that need to be constructed or
799 // destructed by the end of the function
800 unhandled.insert( field );
801 }
802 }
803 }
804 }
805 Parent::visit( function );
806
807 // remove the unhandled objects from usedUninit, because a call is inserted
808 // to handle them - only objects that are later constructed are used uninitialized.
809 std::set< DeclarationWithType * > diff;
810 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ) );
811 for ( DeclarationWithType * member : diff ) {
812 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", member->get_name(), " used before being constructed" );
813 }
814
815 if ( ! unhandled.empty() ) {
816 // need to explicitly re-add function parameters in order to resolve copy constructors
817 enterScope();
818 maybeAccept( function->get_functionType(), *this );
819
820 // need to iterate through members in reverse in order for
821 // ctor/dtor statements to come out in the right order
822 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
823 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
824 // skip non-DWT members
825 if ( ! field ) continue;
826 // skip handled members
827 if ( ! unhandled.count( field ) ) continue;
828
829 // insert and resolve default/copy constructor call for each field that's unhandled
830 std::list< Statement * > stmt;
831 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
832 deref->get_args().push_back( new VariableExpr( thisParam ) );
833
834 Expression * arg2 = 0;
835 if ( isCopyConstructor( function ) ) {
836 // if copy ctor, need to pass second-param-of-this-function.field
837 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
838 assert( params.size() == 2 );
839 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
840 }
841 InitExpander srcParam( arg2 );
842 SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
843
844 assert( stmt.size() <= 1 );
845 if ( stmt.size() == 1 ) {
846 Statement * callStmt = stmt.front();
847
848 MutatingResolver resolver( *this );
849 try {
850 callStmt->acceptMutator( resolver );
851 if ( isCtor ) {
852 function->get_statements()->push_front( callStmt );
853 } else {
854 // destructor statements should be added at the end
855 function->get_statements()->push_back( callStmt );
856 }
857 } catch ( SemanticError & error ) {
858 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
859 }
860 }
861 }
862 leaveScope();
863 }
864 }
865
866 void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
867 if ( ! checkWarnings( function ) ) return;
868
869 std::string fname = getFunctionName( appExpr );
870 if ( fname == function->get_name() ) {
871 // call to same kind of function
872 Expression * firstParam = appExpr->get_args().front();
873
874 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
875 // if calling another constructor on thisParam, assume that function handles
876 // all members - if it doesn't a warning will appear in that function.
877 if ( varExpr->get_var() == thisParam ) {
878 unhandled.clear();
879 }
880 } else {
881 // if first parameter is a member expression then
882 // remove the member from unhandled set.
883 handleFirstParam( firstParam );
884 }
885 }
886
887 Parent::visit( appExpr );
888 }
889
890 void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
891 using namespace std;
892 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
893 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
894 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
895 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
896 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
897 if ( varExpr->get_var() == thisParam ) {
898 unhandled.erase( memberExpr->get_member() );
899 }
900 }
901 }
902 }
903 }
904 }
905 }
906
907 void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
908 if ( ! checkWarnings( function ) ) return;
909 if ( ! isCtor ) return;
910
911 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
912 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
913 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
914 if ( varExpr->get_var() == thisParam ) {
915 if ( unhandled.count( memberExpr->get_member() ) ) {
916 // emit a warning because a member was used before it was constructed
917 usedUninit.insert( memberExpr->get_member() );
918 }
919 }
920 }
921 }
922 }
923 Parent::visit( memberExpr );
924 }
925
926 template< typename Visitor, typename... Params >
927 void error( Visitor & v, const Params &... params ) {
928 v.errors.append( toString( params... ) );
929 }
930
931 template< typename... Params >
932 void GenStructMemberCalls::emit( const Params &... params ) {
933 // toggle warnings vs. errors here.
934 // warn( params... );
935 error( *this, params... );
936 }
937
938 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
939 // add object to the indexer assumes that there will be no name collisions
940 // in generated code. If this changes, add mutate methods for entities with
941 // scope and call {enter,leave}Scope explicitly.
942 objectDecl->accept( indexer );
943 return objectDecl;
944 }
945
946 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
947 return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
948 }
949
950 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
951 static UniqueName tempNamer( "_tmp_ctor_expr" );
952 assert( ctorExpr->get_results().size() == 1 );
953 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, ctorExpr->get_results().front()->clone(), nullptr );
954 addDeclaration( tmp );
955
956 ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
957 TypeSubstitution * env = ctorExpr->get_env();
958 ctorExpr->set_callExpr( nullptr );
959 ctorExpr->set_env( nullptr );
960
961 Expression *& firstArg = callExpr->get_args().front();
962 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
963 assign->get_args().push_back( new VariableExpr( tmp ) );
964 assign->get_args().push_back( firstArg );
965 cloneAll( ctorExpr->get_results(), assign->get_results() );
966 firstArg = assign;
967
968 CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
969 commaExpr->set_env( env );
970 delete ctorExpr;
971 return commaExpr;
972 }
973 } // namespace
974} // namespace InitTweak
975
976// Local Variables: //
977// tab-width: 4 //
978// mode: c++ //
979// compile-command: "make install" //
980// End: //
Note: See TracBrowser for help on using the repository browser.