source: src/InitTweak/GenInit.cc@ f5ec35a

Last change on this file since f5ec35a was c6b4432, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Remove BaseSyntaxNode and clean-up.

  • Property mode set to 100644
File size: 14.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// GenInit.cc -- Generate initializers, and other stuff.
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/SemanticError.h" // for SemanticError
32#include "Common/ToString.hpp" // for toCString
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/GenImplicitCall.hpp" // for genImplicitCall
40#include "SymTab/Mangler.h" // for Mangler
41#include "Tuples/Tuples.h" // for maybeImpure
42#include "Validate/FindSpecialDecls.h" // for SizeType
43
44namespace InitTweak {
45
46namespace {
47
48# warning Remove the _New suffix after the conversion is complete.
49
50 // Outer pass finds declarations, for their type could wrap a type that needs hoisting
51 struct HoistArrayDimension_NoResolve_New final :
52 public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting,
53 public ast::WithGuards, public ast::WithConstTranslationUnit,
54 public ast::WithVisitorRef<HoistArrayDimension_NoResolve_New>,
55 public ast::WithSymbolTableX<ast::SymbolTable::ErrorDetection::IgnoreErrors> {
56
57 // Inner pass looks within a type, for a part that depends on an expression
58 struct HoistDimsFromTypes final :
59 public ast::WithShortCircuiting, public ast::WithGuards {
60
61 HoistArrayDimension_NoResolve_New * outer;
62 HoistDimsFromTypes( HoistArrayDimension_NoResolve_New * outer ) : outer(outer) {}
63
64 // Only intended for visiting through types.
65 // Tolerate, and short-circuit at, the dimension expression of an array type.
66 // (We'll operate on the dimension expression of an array type directly
67 // from the parent type, not by visiting through it)
68 // Look inside type exprs.
69 void previsit( const ast::Node * ) {
70 assert( false && "unsupported node type" );
71 };
72 const ast::Expr * allowedExpr = nullptr;
73 void previsit( const ast::Type * ) {
74 GuardValue( allowedExpr ) = nullptr;
75 }
76 void previsit( const ast::ArrayType * t ) {
77 GuardValue( allowedExpr ) = t->dimension.get();
78 }
79 void previsit( const ast::PointerType * t ) {
80 GuardValue( allowedExpr ) = t->dimension.get();
81 }
82 void previsit( const ast::TypeofType * t ) {
83 GuardValue( allowedExpr ) = t->expr.get();
84 }
85 void previsit( const ast::Expr * e ) {
86 assert( e == allowedExpr &&
87 "only expecting to visit exprs that are dimension exprs or typeof(-) inner exprs" );
88
89 // Skip the tolerated expressions
90 visit_children = false;
91 }
92 void previsit( const ast::TypeExpr * ) {}
93
94 const ast::Type * postvisit(
95 const ast::ArrayType * arrayType ) {
96 static UniqueName dimensionName( "_array_dim" );
97
98 if ( nullptr == arrayType->dimension ) { // if no dimension is given, don't presume to invent one
99 return arrayType;
100 }
101
102 // find size_t; use it as the type for a dim expr
103 ast::ptr<ast::Type> dimType = outer->transUnit().global.sizeType;
104 assert( dimType );
105 add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) );
106
107 // Special-case handling: leave the user's dimension expression alone
108 // - requires the user to have followed a careful convention
109 // - may apply to extremely simple applications, but only as windfall
110 // - users of advanced applications will be following the convention on purpose
111 // - CFA maintainers must protect the criteria against leaving too much alone
112
113 // Actual leave-alone cases following are conservative approximations of "cannot vary"
114
115 // Leave alone: literals and enum constants
116 if ( dynamic_cast< const ast::ConstantExpr * >( arrayType->dimension.get() ) ) {
117 return arrayType;
118 }
119
120 // Leave alone: direct use of an object declared to be const
121 const ast::NameExpr * dimn = dynamic_cast< const ast::NameExpr * >( arrayType->dimension.get() );
122 if ( dimn ) {
123 std::vector<ast::SymbolTable::IdData> dimnDefs = outer->symtab.lookupId( dimn->name );
124 if ( dimnDefs.size() == 1 ) {
125 const ast::DeclWithType * dimnDef = dimnDefs[0].id.get();
126 assert( dimnDef && "symbol table binds a name to nothing" );
127 const ast::ObjectDecl * dimOb = dynamic_cast< const ast::ObjectDecl * >( dimnDef );
128 if( dimOb ) {
129 const ast::Type * dimTy = dimOb->type.get();
130 assert( dimTy && "object declaration bearing no type" );
131 // must not hoist some: size_t
132 // must hoist all: pointers and references
133 // the analysis is conservative; BasicType is a simple approximation
134 if ( dynamic_cast< const ast::BasicType * >( dimTy ) ||
135 dynamic_cast< const ast::SueInstType<ast::EnumDecl> * >( dimTy ) ) {
136 if ( dimTy->is_const() ) {
137 // The dimension is certainly re-evaluable, giving the same answer each time.
138 // Our user might be hoping to write the array type in multiple places, having them unify.
139 // Leave the type alone.
140
141 // We believe the new criterion leaves less alone than the old criterion.
142 // Thus, the old criterion should have left the current case alone.
143 // Catch cases that weren't thought through.
144 assert( !Tuples::maybeImpure( arrayType->dimension ) );
145
146 return arrayType;
147 }
148 };
149 }
150 }
151 }
152
153 // Leave alone: any sizeof expression (answer cannot vary during current lexical scope)
154 const ast::SizeofExpr * sz = dynamic_cast< const ast::SizeofExpr * >( arrayType->dimension.get() );
155 if ( sz ) {
156 return arrayType;
157 }
158
159 // General-case handling: change the array-type's dim expr (hoist the user-given content out of the type)
160 // - always safe
161 // - user-unnoticeable in common applications (benign noise in -CFA output)
162 // - may annoy a responsible user of advanced applications (but they can work around)
163 // - protects against misusing advanced features
164 //
165 // The hoist, by example, is:
166 // FROM USER: float a[ rand() ];
167 // TO GCC: const size_t __len_of_a = rand(); float a[ __len_of_a ];
168
169 ast::ObjectDecl * arrayDimension = new ast::ObjectDecl(
170 arrayType->dimension->location,
171 dimensionName.newName(),
172 dimType,
173 new ast::SingleInit(
174 arrayType->dimension->location,
175 arrayType->dimension
176 )
177 );
178
179 ast::ArrayType * mutType = ast::mutate( arrayType );
180 mutType->dimension = new ast::VariableExpr(
181 arrayDimension->location, arrayDimension );
182 outer->declsToAddBefore.push_back( arrayDimension );
183
184 return mutType;
185 } // postvisit( const ast::ArrayType * )
186 }; // struct HoistDimsFromTypes
187
188 ast::Storage::Classes storageClasses;
189 void previsit(
190 const ast::ObjectDecl * decl ) {
191 GuardValue( storageClasses ) = decl->storage;
192 }
193
194 const ast::DeclWithType * postvisit(
195 const ast::ObjectDecl * objectDecl ) {
196
197 if ( !isInFunction() || storageClasses.is_static ) {
198 return objectDecl;
199 }
200
201 const ast::Type * mid = objectDecl->type;
202
203 ast::Pass<HoistDimsFromTypes> hoist{this};
204 const ast::Type * result = mid->accept( hoist );
205
206 return mutate_field( objectDecl, &ast::ObjectDecl::type, result );
207 }
208 };
209
210
211
212
213 struct ReturnFixer_New final :
214 public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting {
215 void previsit( const ast::FunctionDecl * decl );
216 const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt );
217 private:
218 const ast::FunctionDecl * funcDecl = nullptr;
219 };
220
221 void ReturnFixer_New::previsit( const ast::FunctionDecl * decl ) {
222 if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false;
223 GuardValue( funcDecl ) = decl;
224 }
225
226 const ast::ReturnStmt * ReturnFixer_New::previsit(
227 const ast::ReturnStmt * stmt ) {
228 auto & returns = funcDecl->returns;
229 assert( returns.size() < 2 );
230 // Hands off if the function returns a reference.
231 // Don't allocate a temporary if the address is returned.
232 if ( stmt->expr && 1 == returns.size() ) {
233 ast::ptr<ast::DeclWithType> retDecl = returns.front();
234 if ( isConstructable( retDecl->get_type() ) ) {
235 // Explicitly construct the return value using the return
236 // expression and the retVal object.
237 assertf( "" != retDecl->name,
238 "Function %s has unnamed return value.\n",
239 funcDecl->name.c_str() );
240
241 auto retVal = retDecl.strict_as<ast::ObjectDecl>();
242 if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) {
243 // Check if the return statement is already set up.
244 if ( varExpr->var == retVal ) return stmt;
245 }
246 ast::ptr<ast::Stmt> ctorStmt = genCtorDtor(
247 retVal->location, "?{}", retVal, stmt->expr );
248 assertf( ctorStmt,
249 "ReturnFixer: genCtorDtor returned nullptr: %s / %s",
250 toString( retVal ).c_str(),
251 toString( stmt->expr ).c_str() );
252 stmtsToAddBefore.push_back( ctorStmt );
253
254 // Return the retVal object.
255 ast::ReturnStmt * mutStmt = ast::mutate( stmt );
256 mutStmt->expr = new ast::VariableExpr(
257 stmt->location, retDecl );
258 return mutStmt;
259 }
260 }
261 return stmt;
262 }
263
264} // namespace
265
266 void genInit( ast::TranslationUnit & transUnit ) {
267 ast::Pass<HoistArrayDimension_NoResolve_New>::run( transUnit );
268 ast::Pass<ReturnFixer_New>::run( transUnit );
269 }
270
271 void fixReturnStatements( ast::TranslationUnit & transUnit ) {
272 ast::Pass<ReturnFixer_New>::run( transUnit );
273 }
274
275 bool ManagedTypes_new::isManaged( const ast::Type * type ) const {
276 // references are never constructed
277 if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false;
278 if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) {
279 // tuple is also managed if any of its components are managed
280 for (auto & component : tupleType->types) {
281 if (isManaged(component)) return true;
282 }
283 }
284 // need to clear and reset qualifiers when determining if a type is managed
285 // ValueGuard< Type::Qualifiers > qualifiers( type->get_qualifiers() );
286 auto tmp = shallowCopy(type);
287 tmp->qualifiers = {};
288 // delete tmp at return
289 ast::ptr<ast::Type> guard = tmp;
290 // 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)
291 return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp );
292 }
293
294 bool ManagedTypes_new::isManaged( const ast::ObjectDecl * objDecl ) const {
295 const ast::Type * type = objDecl->type;
296 while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) {
297 // must always construct VLAs with an initializer, since this is an error in C
298 if ( at->isVarLen && objDecl->init ) return true;
299 type = at->base;
300 }
301 return isManaged( type );
302 }
303
304 void ManagedTypes_new::handleDWT( const ast::DeclWithType * dwt ) {
305 // if this function is a user-defined constructor or destructor, mark down the type as "managed"
306 if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) {
307 auto & params = GenPoly::getFunctionType( dwt->get_type())->params;
308 assert( ! params.empty() );
309 // Type * type = InitTweak::getPointerBase( params.front() );
310 // assert( type );
311 managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
312 }
313 }
314
315 void ManagedTypes_new::handleStruct( const ast::StructDecl * aggregateDecl ) {
316 // don't construct members, but need to take note if there is a managed member,
317 // because that means that this type is also managed
318 for ( auto & member : aggregateDecl->members ) {
319 if ( auto field = member.as<ast::ObjectDecl>() ) {
320 if ( isManaged( field ) ) {
321 // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that
322 // polymorphic constructors make generic types managed types
323 ast::StructInstType inst( aggregateDecl );
324 managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) );
325 break;
326 }
327 }
328 }
329 }
330
331 void ManagedTypes_new::beginScope() { managedTypes.beginScope(); }
332 void ManagedTypes_new::endScope() { managedTypes.endScope(); }
333
334 ast::ptr<ast::Stmt> genCtorDtor (const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg) {
335 assertf(objDecl, "genCtorDtor passed null objDecl");
336 InitExpander_new srcParam(arg);
337 return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl);
338 }
339
340ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) {
341 // call into genImplicitCall from Autogen.h to generate calls to ctor/dtor for each
342 // constructable object
343 InitExpander_new srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr };
344 ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl);
345
346 ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall(
347 srcParam, dstParam, loc, "?{}", objDecl );
348 ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall(
349 nullParam, dstParam, loc, "^?{}", objDecl,
350 SymTab::LoopBackward );
351
352 // check that either both ctor and dtor are present, or neither
353 assert( (bool)ctor == (bool)dtor );
354
355 if ( ctor ) {
356 // need to remember init expression, in case no ctors exist. If ctor does exist, want to
357 // use ctor expression instead of init.
358 ctor.strict_as< ast::ImplicitCtorDtorStmt >();
359 dtor.strict_as< ast::ImplicitCtorDtorStmt >();
360
361 return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init };
362 }
363
364 return nullptr;
365}
366
367} // namespace InitTweak
368
369// Local Variables: //
370// tab-width: 4 //
371// mode: c++ //
372// compile-command: "make install" //
373// End: //
Note: See TracBrowser for help on using the repository browser.