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 | // GenInit.cc -- |
---|
8 | // |
---|
9 | // Author : Rob Schluntz |
---|
10 | // Created On : Mon May 18 07:44:20 2015 |
---|
11 | // Last Modified By : Andrew Beach |
---|
12 | // Last Modified On : Mon Oct 25 13:53:00 2021 |
---|
13 | // Update Count : 186 |
---|
14 | // |
---|
15 | #include "GenInit.h" |
---|
16 | |
---|
17 | #include <stddef.h> // for NULL |
---|
18 | #include <algorithm> // for any_of |
---|
19 | #include <cassert> // for assert, strict_dynamic_cast, assertf |
---|
20 | #include <deque> |
---|
21 | #include <iterator> // for back_inserter, inserter, back_inse... |
---|
22 | #include <list> // for _List_iterator, list |
---|
23 | |
---|
24 | #include "AST/Decl.hpp" |
---|
25 | #include "AST/Init.hpp" |
---|
26 | #include "AST/Pass.hpp" |
---|
27 | #include "AST/Node.hpp" |
---|
28 | #include "AST/Stmt.hpp" |
---|
29 | #include "CompilationState.h" |
---|
30 | #include "CodeGen/OperatorTable.h" |
---|
31 | #include "Common/PassVisitor.h" // for PassVisitor, WithGuards, WithShort... |
---|
32 | #include "Common/SemanticError.h" // for SemanticError |
---|
33 | #include "Common/UniqueName.h" // for UniqueName |
---|
34 | #include "Common/utility.h" // for ValueGuard, maybeClone |
---|
35 | #include "GenPoly/GenPoly.h" // for getFunctionType, isPolyType |
---|
36 | #include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::const_iter... |
---|
37 | #include "InitTweak.h" // for isConstExpr, InitExpander, checkIn... |
---|
38 | #include "ResolvExpr/Resolver.h" |
---|
39 | #include "SymTab/Autogen.h" // for genImplicitCall |
---|
40 | #include "SymTab/Mangler.h" // for Mangler |
---|
41 | #include "SynTree/LinkageSpec.h" // for isOverridable, C |
---|
42 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType |
---|
43 | #include "SynTree/Expression.h" // for VariableExpr, UntypedExpr, Address... |
---|
44 | #include "SynTree/Initializer.h" // for ConstructorInit, SingleInit, Initi... |
---|
45 | #include "SynTree/Label.h" // for Label |
---|
46 | #include "SynTree/Mutator.h" // for mutateAll |
---|
47 | #include "SynTree/Statement.h" // for CompoundStmt, ImplicitCtorDtorStmt |
---|
48 | #include "SynTree/Type.h" // for Type, ArrayType, Type::Qualifiers |
---|
49 | #include "SynTree/Visitor.h" // for acceptAll, maybeAccept |
---|
50 | #include "Tuples/Tuples.h" // for maybeImpure |
---|
51 | #include "Validate/FindSpecialDecls.h" // for SizeType |
---|
52 | |
---|
53 | namespace InitTweak { |
---|
54 | namespace { |
---|
55 | const std::list<Label> noLabels; |
---|
56 | const std::list<Expression *> noDesignators; |
---|
57 | } |
---|
58 | |
---|
59 | struct ReturnFixer : public WithStmtsToAdd, public WithGuards { |
---|
60 | /// consistently allocates a temporary variable for the return value |
---|
61 | /// of a function so that anything which the resolver decides can be constructed |
---|
62 | /// into the return type of a function can be returned. |
---|
63 | static void makeReturnTemp( std::list< Declaration * > &translationUnit ); |
---|
64 | |
---|
65 | void premutate( FunctionDecl *functionDecl ); |
---|
66 | void premutate( ReturnStmt * returnStmt ); |
---|
67 | |
---|
68 | protected: |
---|
69 | FunctionType * ftype = nullptr; |
---|
70 | std::string funcName; |
---|
71 | }; |
---|
72 | |
---|
73 | struct CtorDtor : public WithGuards, public WithShortCircuiting, public WithVisitorRef<CtorDtor> { |
---|
74 | /// create constructor and destructor statements for object declarations. |
---|
75 | /// the actual call statements will be added in after the resolver has run |
---|
76 | /// so that the initializer expression is only removed if a constructor is found |
---|
77 | /// and the same destructor call is inserted in all of the appropriate locations. |
---|
78 | static void generateCtorDtor( std::list< Declaration * > &translationUnit ); |
---|
79 | |
---|
80 | void previsit( ObjectDecl * ); |
---|
81 | void previsit( FunctionDecl *functionDecl ); |
---|
82 | |
---|
83 | // should not traverse into any of these declarations to find objects |
---|
84 | // that need to be constructed or destructed |
---|
85 | void previsit( StructDecl *aggregateDecl ); |
---|
86 | void previsit( AggregateDecl * ) { visit_children = false; } |
---|
87 | void previsit( NamedTypeDecl * ) { visit_children = false; } |
---|
88 | void previsit( FunctionType * ) { visit_children = false; } |
---|
89 | |
---|
90 | void previsit( CompoundStmt * compoundStmt ); |
---|
91 | |
---|
92 | private: |
---|
93 | // set of mangled type names for which a constructor or destructor exists in the current scope. |
---|
94 | // these types require a ConstructorInit node to be generated, anything else is a POD type and thus |
---|
95 | // should not have a ConstructorInit generated. |
---|
96 | |
---|
97 | ManagedTypes managedTypes; |
---|
98 | bool inFunction = false; |
---|
99 | }; |
---|
100 | |
---|
101 | struct HoistArrayDimension final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards, public WithIndexer { |
---|
102 | /// hoist dimension from array types in object declaration so that it uses a single |
---|
103 | /// const variable of type size_t, so that side effecting array dimensions are only |
---|
104 | /// computed once. |
---|
105 | static void hoistArrayDimension( std::list< Declaration * > & translationUnit ); |
---|
106 | |
---|
107 | void premutate( ObjectDecl * objectDecl ); |
---|
108 | DeclarationWithType * postmutate( ObjectDecl * objectDecl ); |
---|
109 | void premutate( FunctionDecl *functionDecl ); |
---|
110 | // should not traverse into any of these declarations to find objects |
---|
111 | // that need to be constructed or destructed |
---|
112 | void premutate( AggregateDecl * ) { visit_children = false; } |
---|
113 | void premutate( NamedTypeDecl * ) { visit_children = false; } |
---|
114 | void premutate( FunctionType * ) { visit_children = false; } |
---|
115 | |
---|
116 | // need this so that enumerators are added to the indexer, due to premutate(AggregateDecl *) |
---|
117 | void premutate( EnumDecl * ) {} |
---|
118 | |
---|
119 | void hoist( Type * type ); |
---|
120 | |
---|
121 | Type::StorageClasses storageClasses; |
---|
122 | bool inFunction = false; |
---|
123 | }; |
---|
124 | |
---|
125 | struct HoistArrayDimension_NoResolve final : public WithDeclsToAdd, public WithShortCircuiting, public WithGuards { |
---|
126 | /// hoist dimension from array types in object declaration so that it uses a single |
---|
127 | /// const variable of type size_t, so that side effecting array dimensions are only |
---|
128 | /// computed once. |
---|
129 | static void hoistArrayDimension( std::list< Declaration * > & translationUnit ); |
---|
130 | |
---|
131 | void premutate( ObjectDecl * objectDecl ); |
---|
132 | DeclarationWithType * postmutate( ObjectDecl * objectDecl ); |
---|
133 | void premutate( FunctionDecl *functionDecl ); |
---|
134 | // should not traverse into any of these declarations to find objects |
---|
135 | // that need to be constructed or destructed |
---|
136 | void premutate( AggregateDecl * ) { visit_children = false; } |
---|
137 | void premutate( NamedTypeDecl * ) { visit_children = false; } |
---|
138 | void premutate( FunctionType * ) { visit_children = false; } |
---|
139 | |
---|
140 | void hoist( Type * type ); |
---|
141 | |
---|
142 | Type::StorageClasses storageClasses; |
---|
143 | bool inFunction = false; |
---|
144 | }; |
---|
145 | |
---|
146 | void genInit( std::list< Declaration * > & translationUnit ) { |
---|
147 | if (!useNewAST) { |
---|
148 | HoistArrayDimension::hoistArrayDimension( translationUnit ); |
---|
149 | } |
---|
150 | else { |
---|
151 | HoistArrayDimension_NoResolve::hoistArrayDimension( translationUnit ); |
---|
152 | } |
---|
153 | fixReturnStatements( translationUnit ); |
---|
154 | |
---|
155 | if (!useNewAST) { |
---|
156 | CtorDtor::generateCtorDtor( translationUnit ); |
---|
157 | } |
---|
158 | } |
---|
159 | |
---|
160 | void fixReturnStatements( std::list< Declaration * > & translationUnit ) { |
---|
161 | PassVisitor<ReturnFixer> fixer; |
---|
162 | mutateAll( translationUnit, fixer ); |
---|
163 | } |
---|
164 | |
---|
165 | void ReturnFixer::premutate( ReturnStmt *returnStmt ) { |
---|
166 | std::list< DeclarationWithType * > & returnVals = ftype->get_returnVals(); |
---|
167 | assert( returnVals.size() == 0 || returnVals.size() == 1 ); |
---|
168 | // hands off if the function returns a reference - we don't want to allocate a temporary if a variable's address |
---|
169 | // is being returned |
---|
170 | if ( returnStmt->expr && returnVals.size() == 1 && isConstructable( returnVals.front()->get_type() ) ) { |
---|
171 | // explicitly construct the return value using the return expression and the retVal object |
---|
172 | assertf( returnVals.front()->name != "", "Function %s has unnamed return value\n", funcName.c_str() ); |
---|
173 | |
---|
174 | ObjectDecl * retVal = strict_dynamic_cast< ObjectDecl * >( returnVals.front() ); |
---|
175 | if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( returnStmt->expr ) ) { |
---|
176 | // return statement has already been mutated - don't need to do it again |
---|
177 | if ( varExpr->var == retVal ) return; |
---|
178 | } |
---|
179 | Statement * stmt = genCtorDtor( "?{}", retVal, returnStmt->expr ); |
---|
180 | assertf( stmt, "ReturnFixer: genCtorDtor returned nullptr: %s / %s", toString( retVal ).c_str(), toString( returnStmt->expr ).c_str() ); |
---|
181 | stmtsToAddBefore.push_back( stmt ); |
---|
182 | |
---|
183 | // return the retVal object |
---|
184 | returnStmt->expr = new VariableExpr( returnVals.front() ); |
---|
185 | } // if |
---|
186 | } |
---|
187 | |
---|
188 | void ReturnFixer::premutate( FunctionDecl *functionDecl ) { |
---|
189 | GuardValue( ftype ); |
---|
190 | GuardValue( funcName ); |
---|
191 | |
---|
192 | ftype = functionDecl->type; |
---|
193 | funcName = functionDecl->name; |
---|
194 | } |
---|
195 | |
---|
196 | // precompute array dimension expression, because constructor generation may duplicate it, |
---|
197 | // which would be incorrect if it is a side-effecting computation. |
---|
198 | void HoistArrayDimension::hoistArrayDimension( std::list< Declaration * > & translationUnit ) { |
---|
199 | PassVisitor<HoistArrayDimension> hoister; |
---|
200 | mutateAll( translationUnit, hoister ); |
---|
201 | } |
---|
202 | |
---|
203 | void HoistArrayDimension::premutate( ObjectDecl * objectDecl ) { |
---|
204 | GuardValue( storageClasses ); |
---|
205 | storageClasses = objectDecl->get_storageClasses(); |
---|
206 | } |
---|
207 | |
---|
208 | DeclarationWithType * HoistArrayDimension::postmutate( ObjectDecl * objectDecl ) { |
---|
209 | hoist( objectDecl->get_type() ); |
---|
210 | return objectDecl; |
---|
211 | } |
---|
212 | |
---|
213 | void HoistArrayDimension::hoist( Type * type ) { |
---|
214 | // if in function, generate const size_t var |
---|
215 | static UniqueName dimensionName( "_array_dim" ); |
---|
216 | |
---|
217 | // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension. |
---|
218 | if ( ! inFunction ) return; |
---|
219 | if ( storageClasses.is_static ) return; |
---|
220 | |
---|
221 | if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) { |
---|
222 | if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist? |
---|
223 | |
---|
224 | // need to resolve array dimensions in order to accurately determine if constexpr |
---|
225 | ResolvExpr::findSingleExpression( arrayType->dimension, Validate::SizeType->clone(), indexer ); |
---|
226 | // array is variable-length when the dimension is not constexpr |
---|
227 | arrayType->isVarLen = ! isConstExpr( arrayType->dimension ); |
---|
228 | // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects. |
---|
229 | // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve |
---|
230 | // still try to detect constant expressions |
---|
231 | if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return; |
---|
232 | |
---|
233 | ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) ); |
---|
234 | arrayDimension->get_type()->set_const( true ); |
---|
235 | |
---|
236 | arrayType->set_dimension( new VariableExpr( arrayDimension ) ); |
---|
237 | declsToAddBefore.push_back( arrayDimension ); |
---|
238 | |
---|
239 | hoist( arrayType->get_base() ); |
---|
240 | return; |
---|
241 | } |
---|
242 | } |
---|
243 | |
---|
244 | void HoistArrayDimension::premutate( FunctionDecl * ) { |
---|
245 | GuardValue( inFunction ); |
---|
246 | inFunction = true; |
---|
247 | } |
---|
248 | |
---|
249 | // precompute array dimension expression, because constructor generation may duplicate it, |
---|
250 | // which would be incorrect if it is a side-effecting computation. |
---|
251 | void HoistArrayDimension_NoResolve::hoistArrayDimension( std::list< Declaration * > & translationUnit ) { |
---|
252 | PassVisitor<HoistArrayDimension_NoResolve> hoister; |
---|
253 | mutateAll( translationUnit, hoister ); |
---|
254 | } |
---|
255 | |
---|
256 | void HoistArrayDimension_NoResolve::premutate( ObjectDecl * objectDecl ) { |
---|
257 | GuardValue( storageClasses ); |
---|
258 | storageClasses = objectDecl->get_storageClasses(); |
---|
259 | } |
---|
260 | |
---|
261 | DeclarationWithType * HoistArrayDimension_NoResolve::postmutate( ObjectDecl * objectDecl ) { |
---|
262 | hoist( objectDecl->get_type() ); |
---|
263 | return objectDecl; |
---|
264 | } |
---|
265 | |
---|
266 | void HoistArrayDimension_NoResolve::hoist( Type * type ) { |
---|
267 | // if in function, generate const size_t var |
---|
268 | static UniqueName dimensionName( "_array_dim" ); |
---|
269 | |
---|
270 | // C doesn't allow variable sized arrays at global scope or for static variables, so don't hoist dimension. |
---|
271 | if ( ! inFunction ) return; |
---|
272 | if ( storageClasses.is_static ) return; |
---|
273 | |
---|
274 | if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) { |
---|
275 | if ( ! arrayType->get_dimension() ) return; // xxx - recursive call to hoist? |
---|
276 | // don't need to hoist dimension if it's definitely pure - only need to if there's potential for side effects. |
---|
277 | // xxx - hoisting has no side effects anyways, so don't skip since we delay resolve |
---|
278 | // still try to detect constant expressions |
---|
279 | if ( ! Tuples::maybeImpure( arrayType->dimension ) ) return; |
---|
280 | |
---|
281 | ObjectDecl * arrayDimension = new ObjectDecl( dimensionName.newName(), storageClasses, LinkageSpec::C, 0, Validate::SizeType->clone(), new SingleInit( arrayType->get_dimension() ) ); |
---|
282 | arrayDimension->get_type()->set_const( true ); |
---|
283 | |
---|
284 | arrayType->set_dimension( new VariableExpr( arrayDimension ) ); |
---|
285 | declsToAddBefore.push_back( arrayDimension ); |
---|
286 | |
---|
287 | hoist( arrayType->get_base() ); |
---|
288 | return; |
---|
289 | } |
---|
290 | } |
---|
291 | |
---|
292 | void HoistArrayDimension_NoResolve::premutate( FunctionDecl * ) { |
---|
293 | GuardValue( inFunction ); |
---|
294 | inFunction = true; |
---|
295 | } |
---|
296 | |
---|
297 | namespace { |
---|
298 | |
---|
299 | # warning Remove the _New suffix after the conversion is complete. |
---|
300 | struct HoistArrayDimension_NoResolve_New final : |
---|
301 | public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting, |
---|
302 | public ast::WithGuards, public ast::WithConstTranslationUnit, |
---|
303 | public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New> { |
---|
304 | void previsit( const ast::ObjectDecl * decl ); |
---|
305 | const ast::DeclWithType * postvisit( const ast::ObjectDecl * decl ); |
---|
306 | // Do not look for objects inside there declarations (and type). |
---|
307 | void previsit( const ast::AggregateDecl * ) { visit_children = false; } |
---|
308 | void previsit( const ast::NamedTypeDecl * ) { visit_children = false; } |
---|
309 | void previsit( const ast::FunctionType * ) { visit_children = false; } |
---|
310 | |
---|
311 | const ast::Type * hoist( const ast::Type * type ); |
---|
312 | |
---|
313 | ast::Storage::Classes storageClasses; |
---|
314 | }; |
---|
315 | |
---|
316 | void HoistArrayDimension_NoResolve_New::previsit( |
---|
317 | const ast::ObjectDecl * decl ) { |
---|
318 | GuardValue( storageClasses ) = decl->storage; |
---|
319 | } |
---|
320 | |
---|
321 | const ast::DeclWithType * HoistArrayDimension_NoResolve_New::postvisit( |
---|
322 | const ast::ObjectDecl * objectDecl ) { |
---|
323 | return mutate_field( objectDecl, &ast::ObjectDecl::type, |
---|
324 | hoist( objectDecl->type ) ); |
---|
325 | } |
---|
326 | |
---|
327 | const ast::Type * HoistArrayDimension_NoResolve_New::hoist( |
---|
328 | const ast::Type * type ) { |
---|
329 | static UniqueName dimensionName( "_array_dim" ); |
---|
330 | |
---|
331 | if ( !isInFunction() || storageClasses.is_static ) { |
---|
332 | return type; |
---|
333 | } |
---|
334 | |
---|
335 | if ( auto arrayType = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
336 | if ( nullptr == arrayType->dimension ) { |
---|
337 | return type; |
---|
338 | } |
---|
339 | |
---|
340 | if ( !Tuples::maybeImpure( arrayType->dimension ) ) { |
---|
341 | return type; |
---|
342 | } |
---|
343 | |
---|
344 | ast::ptr<ast::Type> dimType = transUnit().global.sizeType; |
---|
345 | assert( dimType ); |
---|
346 | add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) ); |
---|
347 | |
---|
348 | ast::ObjectDecl * arrayDimension = new ast::ObjectDecl( |
---|
349 | arrayType->dimension->location, |
---|
350 | dimensionName.newName(), |
---|
351 | dimType, |
---|
352 | new ast::SingleInit( |
---|
353 | arrayType->dimension->location, |
---|
354 | arrayType->dimension |
---|
355 | ) |
---|
356 | ); |
---|
357 | |
---|
358 | ast::ArrayType * mutType = ast::mutate( arrayType ); |
---|
359 | mutType->dimension = new ast::VariableExpr( |
---|
360 | arrayDimension->location, arrayDimension ); |
---|
361 | declsToAddBefore.push_back( arrayDimension ); |
---|
362 | |
---|
363 | mutType->base = hoist( mutType->base ); |
---|
364 | return mutType; |
---|
365 | } |
---|
366 | return type; |
---|
367 | } |
---|
368 | |
---|
369 | struct ReturnFixer_New final : |
---|
370 | public ast::WithStmtsToAdd<>, ast::WithGuards { |
---|
371 | void previsit( const ast::FunctionDecl * decl ); |
---|
372 | const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt ); |
---|
373 | private: |
---|
374 | const ast::FunctionDecl * funcDecl = nullptr; |
---|
375 | }; |
---|
376 | |
---|
377 | void ReturnFixer_New::previsit( const ast::FunctionDecl * decl ) { |
---|
378 | GuardValue( funcDecl ) = decl; |
---|
379 | } |
---|
380 | |
---|
381 | const ast::ReturnStmt * ReturnFixer_New::previsit( |
---|
382 | const ast::ReturnStmt * stmt ) { |
---|
383 | auto & returns = funcDecl->returns; |
---|
384 | assert( returns.size() < 2 ); |
---|
385 | // Hands off if the function returns a reference. |
---|
386 | // Don't allocate a temporary if the address is returned. |
---|
387 | if ( stmt->expr && 1 == returns.size() ) { |
---|
388 | ast::ptr<ast::DeclWithType> retDecl = returns.front(); |
---|
389 | if ( isConstructable( retDecl->get_type() ) ) { |
---|
390 | // Explicitly construct the return value using the return |
---|
391 | // expression and the retVal object. |
---|
392 | assertf( "" != retDecl->name, |
---|
393 | "Function %s has unnamed return value.\n", |
---|
394 | funcDecl->name.c_str() ); |
---|
395 | |
---|
396 | auto retVal = retDecl.strict_as<ast::ObjectDecl>(); |
---|
397 | if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) { |
---|
398 | // Check if the return statement is already set up. |
---|
399 | if ( varExpr->var == retVal ) return stmt; |
---|
400 | } |
---|
401 | ast::ptr<ast::Stmt> ctorStmt = genCtorDtor( |
---|
402 | retVal->location, "?{}", retVal, stmt->expr ); |
---|
403 | assertf( ctorStmt, |
---|
404 | "ReturnFixer: genCtorDtor returned nllptr: %s / %s", |
---|
405 | toString( retVal ).c_str(), |
---|
406 | toString( stmt->expr ).c_str() ); |
---|
407 | stmtsToAddBefore.push_back( ctorStmt ); |
---|
408 | |
---|
409 | // Return the retVal object. |
---|
410 | ast::ReturnStmt * mutStmt = ast::mutate( stmt ); |
---|
411 | mutStmt->expr = new ast::VariableExpr( |
---|
412 | stmt->location, retDecl ); |
---|
413 | return mutStmt; |
---|
414 | } |
---|
415 | } |
---|
416 | return stmt; |
---|
417 | } |
---|
418 | |
---|
419 | } // namespace |
---|
420 | |
---|
421 | void genInit( ast::TranslationUnit & transUnit ) { |
---|
422 | ast::Pass<HoistArrayDimension_NoResolve_New>::run( transUnit ); |
---|
423 | ast::Pass<ReturnFixer_New>::run( transUnit ); |
---|
424 | } |
---|
425 | |
---|
426 | void CtorDtor::generateCtorDtor( std::list< Declaration * > & translationUnit ) { |
---|
427 | PassVisitor<CtorDtor> ctordtor; |
---|
428 | acceptAll( translationUnit, ctordtor ); |
---|
429 | } |
---|
430 | |
---|
431 | bool ManagedTypes::isManaged( Type * type ) const { |
---|
432 | // references are never constructed |
---|
433 | if ( dynamic_cast< ReferenceType * >( type ) ) return false; |
---|
434 | // need to clear and reset qualifiers when determining if a type is managed |
---|
435 | ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() ); |
---|
436 | type->get_qualifiers() = Type::Qualifiers(); |
---|
437 | if ( TupleType * tupleType = dynamic_cast< TupleType * > ( type ) ) { |
---|
438 | // tuple is also managed if any of its components are managed |
---|
439 | if ( std::any_of( tupleType->types.begin(), tupleType->types.end(), [&](Type * type) { return isManaged( type ); }) ) { |
---|
440 | return true; |
---|
441 | } |
---|
442 | } |
---|
443 | // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) |
---|
444 | return managedTypes.find( SymTab::Mangler::mangleConcrete( type ) ) != managedTypes.end() || GenPoly::isPolyType( type ); |
---|
445 | } |
---|
446 | |
---|
447 | bool ManagedTypes::isManaged( ObjectDecl * objDecl ) const { |
---|
448 | Type * type = objDecl->get_type(); |
---|
449 | while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) { |
---|
450 | // must always construct VLAs with an initializer, since this is an error in C |
---|
451 | if ( at->isVarLen && objDecl->init ) return true; |
---|
452 | type = at->get_base(); |
---|
453 | } |
---|
454 | return isManaged( type ); |
---|
455 | } |
---|
456 | |
---|
457 | // why is this not just on FunctionDecl? |
---|
458 | void ManagedTypes::handleDWT( DeclarationWithType * dwt ) { |
---|
459 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
460 | if ( ! LinkageSpec::isOverridable( dwt->get_linkage() ) && CodeGen::isCtorDtor( dwt->get_name() ) ) { |
---|
461 | std::list< DeclarationWithType * > & params = GenPoly::getFunctionType( dwt->get_type() )->get_parameters(); |
---|
462 | assert( ! params.empty() ); |
---|
463 | Type * type = InitTweak::getPointerBase( params.front()->get_type() ); |
---|
464 | assert( type ); |
---|
465 | managedTypes.insert( SymTab::Mangler::mangleConcrete( type ) ); |
---|
466 | } |
---|
467 | } |
---|
468 | |
---|
469 | void ManagedTypes::handleStruct( StructDecl * aggregateDecl ) { |
---|
470 | // don't construct members, but need to take note if there is a managed member, |
---|
471 | // because that means that this type is also managed |
---|
472 | for ( Declaration * member : aggregateDecl->get_members() ) { |
---|
473 | if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) { |
---|
474 | if ( isManaged( field ) ) { |
---|
475 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
476 | // polymorphic constructors make generic types managed types |
---|
477 | StructInstType inst( Type::Qualifiers(), aggregateDecl ); |
---|
478 | managedTypes.insert( SymTab::Mangler::mangleConcrete( &inst ) ); |
---|
479 | break; |
---|
480 | } |
---|
481 | } |
---|
482 | } |
---|
483 | } |
---|
484 | |
---|
485 | void ManagedTypes::beginScope() { managedTypes.beginScope(); } |
---|
486 | void ManagedTypes::endScope() { managedTypes.endScope(); } |
---|
487 | |
---|
488 | bool ManagedTypes_new::isManaged( const ast::Type * type ) const { |
---|
489 | // references are never constructed |
---|
490 | if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false; |
---|
491 | if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) { |
---|
492 | // tuple is also managed if any of its components are managed |
---|
493 | for (auto & component : tupleType->types) { |
---|
494 | if (isManaged(component)) return true; |
---|
495 | } |
---|
496 | } |
---|
497 | // need to clear and reset qualifiers when determining if a type is managed |
---|
498 | // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() ); |
---|
499 | auto tmp = shallowCopy(type); |
---|
500 | tmp->qualifiers = {}; |
---|
501 | // delete tmp at return |
---|
502 | ast::ptr<ast::Type> guard = tmp; |
---|
503 | // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) |
---|
504 | return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp ); |
---|
505 | } |
---|
506 | |
---|
507 | bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const { |
---|
508 | const ast::Type * type = objDecl->type; |
---|
509 | while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
510 | // must always construct VLAs with an initializer, since this is an error in C |
---|
511 | if ( at->isVarLen && objDecl->init ) return true; |
---|
512 | type = at->base; |
---|
513 | } |
---|
514 | return isManaged( type ); |
---|
515 | } |
---|
516 | |
---|
517 | void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) { |
---|
518 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
519 | if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) { |
---|
520 | auto & params = GenPoly::getFunctionType( dwt->get_type())->params; |
---|
521 | assert( ! params.empty() ); |
---|
522 | // Type * type = InitTweak::getPointerBase( params.front() ); |
---|
523 | // assert( type ); |
---|
524 | managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
525 | } |
---|
526 | } |
---|
527 | |
---|
528 | void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) { |
---|
529 | // don't construct members, but need to take note if there is a managed member, |
---|
530 | // because that means that this type is also managed |
---|
531 | for ( auto & member : aggregateDecl->members ) { |
---|
532 | if ( auto field = member.as<ast::ObjectDecl>() ) { |
---|
533 | if ( isManaged( field ) ) { |
---|
534 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
535 | // polymorphic constructors make generic types managed types |
---|
536 | ast::StructInstType inst( aggregateDecl ); |
---|
537 | managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
538 | break; |
---|
539 | } |
---|
540 | } |
---|
541 | } |
---|
542 | } |
---|
543 | |
---|
544 | void ManagedTypes_new::beginScope() { managedTypes.beginScope(); } |
---|
545 | void ManagedTypes_new::endScope() { managedTypes.endScope(); } |
---|
546 | |
---|
547 | ImplicitCtorDtorStmt * genCtorDtor( const std::string & fname, ObjectDecl * objDecl, Expression * arg ) { |
---|
548 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor |
---|
549 | assertf( objDecl, "genCtorDtor passed null objDecl" ); |
---|
550 | std::list< Statement * > stmts; |
---|
551 | InitExpander_old srcParam( maybeClone( arg ) ); |
---|
552 | SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), fname, back_inserter( stmts ), objDecl ); |
---|
553 | assert( stmts.size() <= 1 ); |
---|
554 | return stmts.size() == 1 ? strict_dynamic_cast< ImplicitCtorDtorStmt * >( stmts.front() ) : nullptr; |
---|
555 | |
---|
556 | } |
---|
557 | |
---|
558 | ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) { |
---|
559 | assertf(objDecl, "genCtorDtor passed null objDecl"); |
---|
560 | InitExpander_new srcParam(arg); |
---|
561 | return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl); |
---|
562 | } |
---|
563 | |
---|
564 | ConstructorInit * genCtorInit( ObjectDecl * objDecl ) { |
---|
565 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor |
---|
566 | // for each constructable object |
---|
567 | std::list< Statement * > ctor; |
---|
568 | std::list< Statement * > dtor; |
---|
569 | |
---|
570 | InitExpander_old srcParam( objDecl->get_init() ); |
---|
571 | InitExpander_old nullParam( (Initializer *)NULL ); |
---|
572 | SymTab::genImplicitCall( srcParam, new VariableExpr( objDecl ), "?{}", back_inserter( ctor ), objDecl ); |
---|
573 | SymTab::genImplicitCall( nullParam, new VariableExpr( objDecl ), "^?{}", front_inserter( dtor ), objDecl, false ); |
---|
574 | |
---|
575 | // Currently genImplicitCall produces a single Statement - a CompoundStmt |
---|
576 | // which wraps everything that needs to happen. As such, it's technically |
---|
577 | // possible to use a Statement ** in the above calls, but this is inherently |
---|
578 | // unsafe, so instead we take the slightly less efficient route, but will be |
---|
579 | // immediately informed if somehow the above assumption is broken. In this case, |
---|
580 | // we could always wrap the list of statements at this point with a CompoundStmt, |
---|
581 | // but it seems reasonable at the moment for this to be done by genImplicitCall |
---|
582 | // itself. It is possible that genImplicitCall produces no statements (e.g. if |
---|
583 | // an array type does not have a dimension). In this case, it's fine to ignore |
---|
584 | // the object for the purposes of construction. |
---|
585 | assert( ctor.size() == dtor.size() && ctor.size() <= 1 ); |
---|
586 | if ( ctor.size() == 1 ) { |
---|
587 | // need to remember init expression, in case no ctors exist |
---|
588 | // if ctor does exist, want to use ctor expression instead of init |
---|
589 | // push this decision to the resolver |
---|
590 | assert( dynamic_cast< ImplicitCtorDtorStmt * > ( ctor.front() ) && dynamic_cast< ImplicitCtorDtorStmt * > ( dtor.front() ) ); |
---|
591 | return new ConstructorInit( ctor.front(), dtor.front(), objDecl->get_init() ); |
---|
592 | } |
---|
593 | return nullptr; |
---|
594 | } |
---|
595 | |
---|
596 | void CtorDtor::previsit( ObjectDecl * objDecl ) { |
---|
597 | managedTypes.handleDWT( objDecl ); |
---|
598 | // hands off if @=, extern, builtin, etc. |
---|
599 | // even if unmanaged, try to construct global or static if initializer is not constexpr, since this is not legal C |
---|
600 | if ( tryConstruct( objDecl ) && ( managedTypes.isManaged( objDecl ) || ((! inFunction || objDecl->get_storageClasses().is_static ) && ! isConstExpr( objDecl->get_init() ) ) ) ) { |
---|
601 | // constructed objects cannot be designated |
---|
602 | if ( isDesignated( objDecl->get_init() ) ) SemanticError( objDecl, "Cannot include designations in the initializer for a managed Object. If this is really what you want, then initialize with @=.\n" ); |
---|
603 | // constructed objects should not have initializers nested too deeply |
---|
604 | if ( ! checkInitDepth( objDecl ) ) SemanticError( objDecl, "Managed object's initializer is too deep " ); |
---|
605 | |
---|
606 | objDecl->set_init( genCtorInit( objDecl ) ); |
---|
607 | } |
---|
608 | } |
---|
609 | |
---|
610 | void CtorDtor::previsit( FunctionDecl *functionDecl ) { |
---|
611 | visit_children = false; // do not try and construct parameters or forall parameters |
---|
612 | GuardValue( inFunction ); |
---|
613 | inFunction = true; |
---|
614 | |
---|
615 | managedTypes.handleDWT( functionDecl ); |
---|
616 | |
---|
617 | GuardScope( managedTypes ); |
---|
618 | // go through assertions and recursively add seen ctor/dtors |
---|
619 | for ( auto & tyDecl : functionDecl->get_functionType()->get_forall() ) { |
---|
620 | for ( DeclarationWithType *& assertion : tyDecl->get_assertions() ) { |
---|
621 | managedTypes.handleDWT( assertion ); |
---|
622 | } |
---|
623 | } |
---|
624 | |
---|
625 | maybeAccept( functionDecl->get_statements(), *visitor ); |
---|
626 | } |
---|
627 | |
---|
628 | void CtorDtor::previsit( StructDecl *aggregateDecl ) { |
---|
629 | visit_children = false; // do not try to construct and destruct aggregate members |
---|
630 | |
---|
631 | managedTypes.handleStruct( aggregateDecl ); |
---|
632 | } |
---|
633 | |
---|
634 | void CtorDtor::previsit( CompoundStmt * ) { |
---|
635 | GuardScope( managedTypes ); |
---|
636 | } |
---|
637 | |
---|
638 | ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) { |
---|
639 | // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each |
---|
640 | // constructable object |
---|
641 | InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr }; |
---|
642 | ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl); |
---|
643 | |
---|
644 | ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( |
---|
645 | srcParam, dstParam, loc, "?{}", objDecl ); |
---|
646 | ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( |
---|
647 | nullParam, dstParam, loc, "^?{}", objDecl, |
---|
648 | SymTab::LoopBackward ); |
---|
649 | |
---|
650 | // check that either both ctor and dtor are present, or neither |
---|
651 | assert( (bool)ctor == (bool)dtor ); |
---|
652 | |
---|
653 | if ( ctor ) { |
---|
654 | // need to remember init expression, in case no ctors exist. If ctor does exist, want to |
---|
655 | // use ctor expression instead of init. |
---|
656 | ctor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
657 | dtor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
658 | |
---|
659 | return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init }; |
---|
660 | } |
---|
661 | |
---|
662 | return nullptr; |
---|
663 | } |
---|
664 | |
---|
665 | } // namespace InitTweak |
---|
666 | |
---|
667 | // Local Variables: // |
---|
668 | // tab-width: 4 // |
---|
669 | // mode: c++ // |
---|
670 | // compile-command: "make install" // |
---|
671 | // End: // |
---|