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