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