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 | // Validate.cc -- |
---|
8 | // |
---|
9 | // Author : Richard C. Bilson |
---|
10 | // Created On : Sun May 17 21:50:04 2015 |
---|
11 | // Last Modified By : Peter A. Buhr |
---|
12 | // Last Modified On : Mon Aug 28 13:47:23 2017 |
---|
13 | // Update Count : 359 |
---|
14 | // |
---|
15 | |
---|
16 | // The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be |
---|
17 | // as regular in structure as possible. Some assumptions can be made regarding the state of the tree after this pass is |
---|
18 | // complete, including: |
---|
19 | // |
---|
20 | // - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or |
---|
21 | // union. |
---|
22 | // |
---|
23 | // - All enumeration constants have type EnumInstType. |
---|
24 | // |
---|
25 | // - The type "void" never occurs in lists of function parameter or return types. A function |
---|
26 | // taking no arguments has no argument types. |
---|
27 | // |
---|
28 | // - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated |
---|
29 | // by the particular set of type arguments. |
---|
30 | // |
---|
31 | // - Every declaration is assigned a unique id. |
---|
32 | // |
---|
33 | // - No typedef declarations or instances exist; the actual type is substituted for each instance. |
---|
34 | // |
---|
35 | // - Each type, struct, and union definition is followed by an appropriate assignment operator. |
---|
36 | // |
---|
37 | // - Each use of a struct or union is connected to a complete definition of that struct or union, even if that |
---|
38 | // definition occurs later in the input. |
---|
39 | |
---|
40 | #include "Validate.h" |
---|
41 | |
---|
42 | #include <cassert> // for assertf, assert |
---|
43 | #include <cstddef> // for size_t |
---|
44 | #include <list> // for list |
---|
45 | #include <string> // for string |
---|
46 | #include <utility> // for pair |
---|
47 | |
---|
48 | #include "CodeGen/CodeGenerator.h" // for genName |
---|
49 | #include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign |
---|
50 | #include "ControlStruct/Mutate.h" // for ForExprMutator |
---|
51 | #include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd |
---|
52 | #include "Common/ScopedMap.h" // for ScopedMap |
---|
53 | #include "Common/SemanticError.h" // for SemanticError |
---|
54 | #include "Common/UniqueName.h" // for UniqueName |
---|
55 | #include "Common/utility.h" // for operator+, cloneAll, deleteAll |
---|
56 | #include "Concurrency/Keywords.h" // for applyKeywords |
---|
57 | #include "FixFunction.h" // for FixFunction |
---|
58 | #include "Indexer.h" // for Indexer |
---|
59 | #include "InitTweak/GenInit.h" // for fixReturnStatements |
---|
60 | #include "InitTweak/InitTweak.h" // for isCtorDtorAssign |
---|
61 | #include "Parser/LinkageSpec.h" // for C |
---|
62 | #include "ResolvExpr/typeops.h" // for typesCompatible |
---|
63 | #include "SymTab/Autogen.h" // for SizeType |
---|
64 | #include "SynTree/Attribute.h" // for noAttributes, Attribute |
---|
65 | #include "SynTree/Constant.h" // for Constant |
---|
66 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType |
---|
67 | #include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio... |
---|
68 | #include "SynTree/Initializer.h" // for ListInit, Initializer |
---|
69 | #include "SynTree/Label.h" // for operator==, Label |
---|
70 | #include "SynTree/Mutator.h" // for Mutator |
---|
71 | #include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType |
---|
72 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution |
---|
73 | #include "SynTree/Visitor.h" // for Visitor |
---|
74 | |
---|
75 | class CompoundStmt; |
---|
76 | class ReturnStmt; |
---|
77 | class SwitchStmt; |
---|
78 | |
---|
79 | #define debugPrint( x ) if ( doDebug ) { std::cout << x; } |
---|
80 | |
---|
81 | namespace SymTab { |
---|
82 | struct HoistStruct final : public WithDeclsToAdd, public WithGuards { |
---|
83 | /// Flattens nested struct types |
---|
84 | static void hoistStruct( std::list< Declaration * > &translationUnit ); |
---|
85 | |
---|
86 | void previsit( EnumInstType * enumInstType ); |
---|
87 | void previsit( StructInstType * structInstType ); |
---|
88 | void previsit( UnionInstType * unionInstType ); |
---|
89 | void previsit( StructDecl * aggregateDecl ); |
---|
90 | void previsit( UnionDecl * aggregateDecl ); |
---|
91 | void previsit( StaticAssertDecl * assertDecl ); |
---|
92 | |
---|
93 | private: |
---|
94 | template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl ); |
---|
95 | |
---|
96 | AggregateDecl * parentAggr = nullptr; |
---|
97 | }; |
---|
98 | |
---|
99 | /// Fix return types so that every function returns exactly one value |
---|
100 | struct ReturnTypeFixer { |
---|
101 | static void fix( std::list< Declaration * > &translationUnit ); |
---|
102 | |
---|
103 | void postvisit( FunctionDecl * functionDecl ); |
---|
104 | void postvisit( FunctionType * ftype ); |
---|
105 | }; |
---|
106 | |
---|
107 | /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers. |
---|
108 | struct EnumAndPointerDecay { |
---|
109 | void previsit( EnumDecl *aggregateDecl ); |
---|
110 | void previsit( FunctionType *func ); |
---|
111 | }; |
---|
112 | |
---|
113 | /// Associates forward declarations of aggregates with their definitions |
---|
114 | struct LinkReferenceToTypes final : public WithIndexer, public WithGuards { |
---|
115 | LinkReferenceToTypes( const Indexer *indexer ); |
---|
116 | void postvisit( TypeInstType *typeInst ); |
---|
117 | |
---|
118 | void postvisit( EnumInstType *enumInst ); |
---|
119 | void postvisit( StructInstType *structInst ); |
---|
120 | void postvisit( UnionInstType *unionInst ); |
---|
121 | void postvisit( TraitInstType *traitInst ); |
---|
122 | |
---|
123 | void postvisit( EnumDecl *enumDecl ); |
---|
124 | void postvisit( StructDecl *structDecl ); |
---|
125 | void postvisit( UnionDecl *unionDecl ); |
---|
126 | void postvisit( TraitDecl * traitDecl ); |
---|
127 | |
---|
128 | void previsit( StructDecl *structDecl ); |
---|
129 | void previsit( UnionDecl *unionDecl ); |
---|
130 | |
---|
131 | void renameGenericParams( std::list< TypeDecl * > & params ); |
---|
132 | |
---|
133 | private: |
---|
134 | const Indexer *local_indexer; |
---|
135 | |
---|
136 | typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType; |
---|
137 | typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType; |
---|
138 | typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType; |
---|
139 | ForwardEnumsType forwardEnums; |
---|
140 | ForwardStructsType forwardStructs; |
---|
141 | ForwardUnionsType forwardUnions; |
---|
142 | /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately |
---|
143 | bool inGeneric = false; |
---|
144 | }; |
---|
145 | |
---|
146 | /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID. |
---|
147 | struct ForallPointerDecay final { |
---|
148 | void previsit( ObjectDecl * object ); |
---|
149 | void previsit( FunctionDecl * func ); |
---|
150 | void previsit( FunctionType * ftype ); |
---|
151 | void previsit( StructDecl * aggrDecl ); |
---|
152 | void previsit( UnionDecl * aggrDecl ); |
---|
153 | }; |
---|
154 | |
---|
155 | struct ReturnChecker : public WithGuards { |
---|
156 | /// Checks that return statements return nothing if their return type is void |
---|
157 | /// and return something if the return type is non-void. |
---|
158 | static void checkFunctionReturns( std::list< Declaration * > & translationUnit ); |
---|
159 | |
---|
160 | void previsit( FunctionDecl * functionDecl ); |
---|
161 | void previsit( ReturnStmt * returnStmt ); |
---|
162 | |
---|
163 | typedef std::list< DeclarationWithType * > ReturnVals; |
---|
164 | ReturnVals returnVals; |
---|
165 | }; |
---|
166 | |
---|
167 | struct EliminateTypedef final : public WithVisitorRef<EliminateTypedef>, public WithGuards { |
---|
168 | EliminateTypedef() : scopeLevel( 0 ) {} |
---|
169 | /// Replaces typedefs by forward declarations |
---|
170 | static void eliminateTypedef( std::list< Declaration * > &translationUnit ); |
---|
171 | |
---|
172 | Type * postmutate( TypeInstType * aggregateUseType ); |
---|
173 | Declaration * postmutate( TypedefDecl * typeDecl ); |
---|
174 | void premutate( TypeDecl * typeDecl ); |
---|
175 | void premutate( FunctionDecl * funcDecl ); |
---|
176 | void premutate( ObjectDecl * objDecl ); |
---|
177 | DeclarationWithType * postmutate( ObjectDecl * objDecl ); |
---|
178 | |
---|
179 | void premutate( CastExpr * castExpr ); |
---|
180 | |
---|
181 | void premutate( CompoundStmt * compoundStmt ); |
---|
182 | CompoundStmt * postmutate( CompoundStmt * compoundStmt ); |
---|
183 | |
---|
184 | void premutate( StructDecl * structDecl ); |
---|
185 | Declaration * postmutate( StructDecl * structDecl ); |
---|
186 | void premutate( UnionDecl * unionDecl ); |
---|
187 | Declaration * postmutate( UnionDecl * unionDecl ); |
---|
188 | void premutate( EnumDecl * enumDecl ); |
---|
189 | Declaration * postmutate( EnumDecl * enumDecl ); |
---|
190 | Declaration * postmutate( TraitDecl * contextDecl ); |
---|
191 | |
---|
192 | void premutate( FunctionType * ftype ); |
---|
193 | |
---|
194 | private: |
---|
195 | template<typename AggDecl> |
---|
196 | AggDecl *handleAggregate( AggDecl * aggDecl ); |
---|
197 | |
---|
198 | template<typename AggDecl> |
---|
199 | void addImplicitTypedef( AggDecl * aggDecl ); |
---|
200 | |
---|
201 | typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr; |
---|
202 | typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap; |
---|
203 | typedef std::map< std::string, TypeDecl * > TypeDeclMap; |
---|
204 | TypedefMap typedefNames; |
---|
205 | TypeDeclMap typedeclNames; |
---|
206 | int scopeLevel; |
---|
207 | bool inFunctionType = false; |
---|
208 | }; |
---|
209 | |
---|
210 | struct VerifyCtorDtorAssign { |
---|
211 | /// ensure that constructors, destructors, and assignment have at least one |
---|
212 | /// parameter, the first of which must be a pointer, and that ctor/dtors have no |
---|
213 | /// return values. |
---|
214 | static void verify( std::list< Declaration * > &translationUnit ); |
---|
215 | |
---|
216 | void previsit( FunctionDecl *funcDecl ); |
---|
217 | }; |
---|
218 | |
---|
219 | /// ensure that generic types have the correct number of type arguments |
---|
220 | struct ValidateGenericParameters { |
---|
221 | void previsit( StructInstType * inst ); |
---|
222 | void previsit( UnionInstType * inst ); |
---|
223 | }; |
---|
224 | |
---|
225 | struct ArrayLength { |
---|
226 | /// for array types without an explicit length, compute the length and store it so that it |
---|
227 | /// is known to the rest of the phases. For example, |
---|
228 | /// int x[] = { 1, 2, 3 }; |
---|
229 | /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
230 | /// here x and y are known at compile-time to have length 3, so change this into |
---|
231 | /// int x[3] = { 1, 2, 3 }; |
---|
232 | /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
233 | static void computeLength( std::list< Declaration * > & translationUnit ); |
---|
234 | |
---|
235 | void previsit( ObjectDecl * objDecl ); |
---|
236 | }; |
---|
237 | |
---|
238 | struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> { |
---|
239 | Type::StorageClasses storageClasses; |
---|
240 | |
---|
241 | void premutate( ObjectDecl *objectDecl ); |
---|
242 | Expression * postmutate( CompoundLiteralExpr *compLitExpr ); |
---|
243 | }; |
---|
244 | |
---|
245 | struct LabelAddressFixer final : public WithGuards { |
---|
246 | std::set< Label > labels; |
---|
247 | |
---|
248 | void premutate( FunctionDecl * funcDecl ); |
---|
249 | Expression * postmutate( AddressExpr * addrExpr ); |
---|
250 | }; |
---|
251 | |
---|
252 | FunctionDecl * dereferenceOperator = nullptr; |
---|
253 | struct FindSpecialDeclarations final { |
---|
254 | void previsit( FunctionDecl * funcDecl ); |
---|
255 | }; |
---|
256 | |
---|
257 | void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) { |
---|
258 | PassVisitor<EnumAndPointerDecay> epc; |
---|
259 | PassVisitor<LinkReferenceToTypes> lrt( nullptr ); |
---|
260 | PassVisitor<ForallPointerDecay> fpd; |
---|
261 | PassVisitor<CompoundLiteral> compoundliteral; |
---|
262 | PassVisitor<ValidateGenericParameters> genericParams; |
---|
263 | PassVisitor<FindSpecialDeclarations> finder; |
---|
264 | PassVisitor<LabelAddressFixer> labelAddrFixer; |
---|
265 | |
---|
266 | EliminateTypedef::eliminateTypedef( translationUnit ); |
---|
267 | HoistStruct::hoistStruct( translationUnit ); // must happen after EliminateTypedef, so that aggregate typedefs occur in the correct order |
---|
268 | ReturnTypeFixer::fix( translationUnit ); // must happen before autogen |
---|
269 | acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes because it is an indexer and needs correct types for mangling |
---|
270 | acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions |
---|
271 | acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes |
---|
272 | VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors |
---|
273 | ReturnChecker::checkFunctionReturns( translationUnit ); |
---|
274 | InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen |
---|
275 | Concurrency::applyKeywords( translationUnit ); |
---|
276 | acceptAll( translationUnit, fpd ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution |
---|
277 | ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines |
---|
278 | autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay |
---|
279 | Concurrency::implementMutexFuncs( translationUnit ); |
---|
280 | Concurrency::implementThreadStarter( translationUnit ); |
---|
281 | mutateAll( translationUnit, compoundliteral ); |
---|
282 | ArrayLength::computeLength( translationUnit ); |
---|
283 | acceptAll( translationUnit, finder ); // xxx - remove this pass soon |
---|
284 | mutateAll( translationUnit, labelAddrFixer ); |
---|
285 | } |
---|
286 | |
---|
287 | void validateType( Type *type, const Indexer *indexer ) { |
---|
288 | PassVisitor<EnumAndPointerDecay> epc; |
---|
289 | PassVisitor<LinkReferenceToTypes> lrt( indexer ); |
---|
290 | PassVisitor<ForallPointerDecay> fpd; |
---|
291 | type->accept( epc ); |
---|
292 | type->accept( lrt ); |
---|
293 | type->accept( fpd ); |
---|
294 | } |
---|
295 | |
---|
296 | void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) { |
---|
297 | PassVisitor<HoistStruct> hoister; |
---|
298 | acceptAll( translationUnit, hoister ); |
---|
299 | } |
---|
300 | |
---|
301 | bool shouldHoist( Declaration *decl ) { |
---|
302 | return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl ); |
---|
303 | } |
---|
304 | |
---|
305 | template< typename AggDecl > |
---|
306 | void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) { |
---|
307 | if ( parentAggr ) { |
---|
308 | // Add elements in stack order corresponding to nesting structure. |
---|
309 | declsToAddBefore.push_front( aggregateDecl ); |
---|
310 | } else { |
---|
311 | GuardValue( parentAggr ); |
---|
312 | parentAggr = aggregateDecl; |
---|
313 | } // if |
---|
314 | // Always remove the hoisted aggregate from the inner structure. |
---|
315 | GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } ); |
---|
316 | } |
---|
317 | |
---|
318 | void HoistStruct::previsit( EnumInstType * inst ) { |
---|
319 | if ( inst->baseEnum && inst->baseEnum->body ) { |
---|
320 | declsToAddBefore.push_front( inst->baseEnum ); |
---|
321 | } |
---|
322 | } |
---|
323 | |
---|
324 | void HoistStruct::previsit( StructInstType * inst ) { |
---|
325 | if ( inst->baseStruct && inst->baseStruct->body ) { |
---|
326 | declsToAddBefore.push_front( inst->baseStruct ); |
---|
327 | } |
---|
328 | } |
---|
329 | |
---|
330 | void HoistStruct::previsit( UnionInstType * inst ) { |
---|
331 | if ( inst->baseUnion && inst->baseUnion->body ) { |
---|
332 | declsToAddBefore.push_front( inst->baseUnion ); |
---|
333 | } |
---|
334 | } |
---|
335 | |
---|
336 | void HoistStruct::previsit( StaticAssertDecl * assertDecl ) { |
---|
337 | if ( parentAggr ) { |
---|
338 | declsToAddBefore.push_back( assertDecl ); |
---|
339 | } |
---|
340 | } |
---|
341 | |
---|
342 | void HoistStruct::previsit( StructDecl * aggregateDecl ) { |
---|
343 | handleAggregate( aggregateDecl ); |
---|
344 | } |
---|
345 | |
---|
346 | void HoistStruct::previsit( UnionDecl * aggregateDecl ) { |
---|
347 | handleAggregate( aggregateDecl ); |
---|
348 | } |
---|
349 | |
---|
350 | void EnumAndPointerDecay::previsit( EnumDecl *enumDecl ) { |
---|
351 | // Set the type of each member of the enumeration to be EnumConstant |
---|
352 | for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) { |
---|
353 | ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i ); |
---|
354 | assert( obj ); |
---|
355 | obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) ); |
---|
356 | } // for |
---|
357 | } |
---|
358 | |
---|
359 | namespace { |
---|
360 | template< typename DWTList > |
---|
361 | void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) { |
---|
362 | auto nvals = dwts.size(); |
---|
363 | bool containsVoid = false; |
---|
364 | for ( auto & dwt : dwts ) { |
---|
365 | // fix each DWT and record whether a void was found |
---|
366 | containsVoid |= fixFunction( dwt ); |
---|
367 | } |
---|
368 | |
---|
369 | // the only case in which "void" is valid is where it is the only one in the list |
---|
370 | if ( containsVoid && ( nvals > 1 || isVarArgs ) ) { |
---|
371 | SemanticError( func, "invalid type void in function type " ); |
---|
372 | } |
---|
373 | |
---|
374 | // one void is the only thing in the list; remove it. |
---|
375 | if ( containsVoid ) { |
---|
376 | delete dwts.front(); |
---|
377 | dwts.clear(); |
---|
378 | } |
---|
379 | } |
---|
380 | } |
---|
381 | |
---|
382 | void EnumAndPointerDecay::previsit( FunctionType *func ) { |
---|
383 | // Fix up parameters and return types |
---|
384 | fixFunctionList( func->parameters, func->isVarArgs, func ); |
---|
385 | fixFunctionList( func->returnVals, false, func ); |
---|
386 | } |
---|
387 | |
---|
388 | LinkReferenceToTypes::LinkReferenceToTypes( const Indexer *other_indexer ) { |
---|
389 | if ( other_indexer ) { |
---|
390 | local_indexer = other_indexer; |
---|
391 | } else { |
---|
392 | local_indexer = &indexer; |
---|
393 | } // if |
---|
394 | } |
---|
395 | |
---|
396 | void LinkReferenceToTypes::postvisit( EnumInstType *enumInst ) { |
---|
397 | EnumDecl *st = local_indexer->lookupEnum( enumInst->get_name() ); |
---|
398 | // it's not a semantic error if the enum is not found, just an implicit forward declaration |
---|
399 | if ( st ) { |
---|
400 | //assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() ); |
---|
401 | enumInst->set_baseEnum( st ); |
---|
402 | } // if |
---|
403 | if ( ! st || st->get_members().empty() ) { |
---|
404 | // use of forward declaration |
---|
405 | forwardEnums[ enumInst->get_name() ].push_back( enumInst ); |
---|
406 | } // if |
---|
407 | } |
---|
408 | |
---|
409 | void checkGenericParameters( ReferenceToType * inst ) { |
---|
410 | for ( Expression * param : inst->parameters ) { |
---|
411 | if ( ! dynamic_cast< TypeExpr * >( param ) ) { |
---|
412 | SemanticError( inst, "Expression parameters for generic types are currently unsupported: " ); |
---|
413 | } |
---|
414 | } |
---|
415 | } |
---|
416 | |
---|
417 | void LinkReferenceToTypes::postvisit( StructInstType *structInst ) { |
---|
418 | StructDecl *st = local_indexer->lookupStruct( structInst->get_name() ); |
---|
419 | // it's not a semantic error if the struct is not found, just an implicit forward declaration |
---|
420 | if ( st ) { |
---|
421 | //assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() ); |
---|
422 | structInst->set_baseStruct( st ); |
---|
423 | } // if |
---|
424 | if ( ! st || st->get_members().empty() ) { |
---|
425 | // use of forward declaration |
---|
426 | forwardStructs[ structInst->get_name() ].push_back( structInst ); |
---|
427 | } // if |
---|
428 | checkGenericParameters( structInst ); |
---|
429 | } |
---|
430 | |
---|
431 | void LinkReferenceToTypes::postvisit( UnionInstType *unionInst ) { |
---|
432 | UnionDecl *un = local_indexer->lookupUnion( unionInst->get_name() ); |
---|
433 | // it's not a semantic error if the union is not found, just an implicit forward declaration |
---|
434 | if ( un ) { |
---|
435 | unionInst->set_baseUnion( un ); |
---|
436 | } // if |
---|
437 | if ( ! un || un->get_members().empty() ) { |
---|
438 | // use of forward declaration |
---|
439 | forwardUnions[ unionInst->get_name() ].push_back( unionInst ); |
---|
440 | } // if |
---|
441 | checkGenericParameters( unionInst ); |
---|
442 | } |
---|
443 | |
---|
444 | template< typename Decl > |
---|
445 | void normalizeAssertions( std::list< Decl * > & assertions ) { |
---|
446 | // ensure no duplicate trait members after the clone |
---|
447 | auto pred = [](Decl * d1, Decl * d2) { |
---|
448 | // only care if they're equal |
---|
449 | DeclarationWithType * dwt1 = dynamic_cast<DeclarationWithType *>( d1 ); |
---|
450 | DeclarationWithType * dwt2 = dynamic_cast<DeclarationWithType *>( d2 ); |
---|
451 | if ( dwt1 && dwt2 ) { |
---|
452 | if ( dwt1->get_name() == dwt2->get_name() && ResolvExpr::typesCompatible( dwt1->get_type(), dwt2->get_type(), SymTab::Indexer() ) ) { |
---|
453 | // std::cerr << "=========== equal:" << std::endl; |
---|
454 | // std::cerr << "d1: " << d1 << std::endl; |
---|
455 | // std::cerr << "d2: " << d2 << std::endl; |
---|
456 | return false; |
---|
457 | } |
---|
458 | } |
---|
459 | return d1 < d2; |
---|
460 | }; |
---|
461 | std::set<Decl *, decltype(pred)> unique_members( assertions.begin(), assertions.end(), pred ); |
---|
462 | // if ( unique_members.size() != assertions.size() ) { |
---|
463 | // std::cerr << "============different" << std::endl; |
---|
464 | // std::cerr << unique_members.size() << " " << assertions.size() << std::endl; |
---|
465 | // } |
---|
466 | |
---|
467 | std::list< Decl * > order; |
---|
468 | order.splice( order.end(), assertions ); |
---|
469 | std::copy_if( order.begin(), order.end(), back_inserter( assertions ), [&]( Decl * decl ) { |
---|
470 | return unique_members.count( decl ); |
---|
471 | }); |
---|
472 | } |
---|
473 | |
---|
474 | // expand assertions from trait instance, performing the appropriate type variable substitutions |
---|
475 | template< typename Iterator > |
---|
476 | void expandAssertions( TraitInstType * inst, Iterator out ) { |
---|
477 | assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toString( inst ).c_str() ); |
---|
478 | std::list< DeclarationWithType * > asserts; |
---|
479 | for ( Declaration * decl : inst->baseTrait->members ) { |
---|
480 | asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) ); |
---|
481 | } |
---|
482 | // substitute trait decl parameters for instance parameters |
---|
483 | applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out ); |
---|
484 | } |
---|
485 | |
---|
486 | void LinkReferenceToTypes::postvisit( TraitDecl * traitDecl ) { |
---|
487 | if ( traitDecl->name == "sized" ) { |
---|
488 | // "sized" is a special trait - flick the sized status on for the type variable |
---|
489 | assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() ); |
---|
490 | TypeDecl * td = traitDecl->parameters.front(); |
---|
491 | td->set_sized( true ); |
---|
492 | } |
---|
493 | |
---|
494 | // move assertions from type parameters into the body of the trait |
---|
495 | for ( TypeDecl * td : traitDecl->parameters ) { |
---|
496 | for ( DeclarationWithType * assert : td->assertions ) { |
---|
497 | if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) { |
---|
498 | expandAssertions( inst, back_inserter( traitDecl->members ) ); |
---|
499 | } else { |
---|
500 | traitDecl->members.push_back( assert->clone() ); |
---|
501 | } |
---|
502 | } |
---|
503 | deleteAll( td->assertions ); |
---|
504 | td->assertions.clear(); |
---|
505 | } // for |
---|
506 | } |
---|
507 | |
---|
508 | void LinkReferenceToTypes::postvisit( TraitInstType * traitInst ) { |
---|
509 | // handle other traits |
---|
510 | TraitDecl *traitDecl = local_indexer->lookupTrait( traitInst->name ); |
---|
511 | if ( ! traitDecl ) { |
---|
512 | SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name ); |
---|
513 | } // if |
---|
514 | if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) { |
---|
515 | SemanticError( traitInst, "incorrect number of trait parameters: " ); |
---|
516 | } // if |
---|
517 | traitInst->baseTrait = traitDecl; |
---|
518 | |
---|
519 | // need to carry over the 'sized' status of each decl in the instance |
---|
520 | for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) { |
---|
521 | TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) ); |
---|
522 | if ( ! expr ) { |
---|
523 | SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " ); |
---|
524 | } |
---|
525 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) { |
---|
526 | TypeDecl * formalDecl = std::get<0>(p); |
---|
527 | TypeDecl * instDecl = inst->get_baseType(); |
---|
528 | if ( formalDecl->get_sized() ) instDecl->set_sized( true ); |
---|
529 | } |
---|
530 | } |
---|
531 | // normalizeAssertions( traitInst->members ); |
---|
532 | } |
---|
533 | |
---|
534 | void LinkReferenceToTypes::postvisit( EnumDecl *enumDecl ) { |
---|
535 | // visit enum members first so that the types of self-referencing members are updated properly |
---|
536 | if ( ! enumDecl->get_members().empty() ) { |
---|
537 | ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() ); |
---|
538 | if ( fwds != forwardEnums.end() ) { |
---|
539 | for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) { |
---|
540 | (*inst )->set_baseEnum( enumDecl ); |
---|
541 | } // for |
---|
542 | forwardEnums.erase( fwds ); |
---|
543 | } // if |
---|
544 | } // if |
---|
545 | } |
---|
546 | |
---|
547 | void LinkReferenceToTypes::renameGenericParams( std::list< TypeDecl * > & params ) { |
---|
548 | // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g. |
---|
549 | // forall(otype T) |
---|
550 | // struct Box { |
---|
551 | // T x; |
---|
552 | // }; |
---|
553 | // forall(otype T) |
---|
554 | // void f(Box(T) b) { |
---|
555 | // ... |
---|
556 | // } |
---|
557 | // The T in Box and the T in f are different, so internally the naming must reflect that. |
---|
558 | GuardValue( inGeneric ); |
---|
559 | inGeneric = ! params.empty(); |
---|
560 | for ( TypeDecl * td : params ) { |
---|
561 | td->name = "__" + td->name + "_generic_"; |
---|
562 | } |
---|
563 | } |
---|
564 | |
---|
565 | void LinkReferenceToTypes::previsit( StructDecl * structDecl ) { |
---|
566 | renameGenericParams( structDecl->parameters ); |
---|
567 | } |
---|
568 | |
---|
569 | void LinkReferenceToTypes::previsit( UnionDecl * unionDecl ) { |
---|
570 | renameGenericParams( unionDecl->parameters ); |
---|
571 | } |
---|
572 | |
---|
573 | void LinkReferenceToTypes::postvisit( StructDecl *structDecl ) { |
---|
574 | // visit struct members first so that the types of self-referencing members are updated properly |
---|
575 | // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their defaults) |
---|
576 | if ( ! structDecl->get_members().empty() ) { |
---|
577 | ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() ); |
---|
578 | if ( fwds != forwardStructs.end() ) { |
---|
579 | for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) { |
---|
580 | (*inst )->set_baseStruct( structDecl ); |
---|
581 | } // for |
---|
582 | forwardStructs.erase( fwds ); |
---|
583 | } // if |
---|
584 | } // if |
---|
585 | } |
---|
586 | |
---|
587 | void LinkReferenceToTypes::postvisit( UnionDecl *unionDecl ) { |
---|
588 | if ( ! unionDecl->get_members().empty() ) { |
---|
589 | ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() ); |
---|
590 | if ( fwds != forwardUnions.end() ) { |
---|
591 | for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) { |
---|
592 | (*inst )->set_baseUnion( unionDecl ); |
---|
593 | } // for |
---|
594 | forwardUnions.erase( fwds ); |
---|
595 | } // if |
---|
596 | } // if |
---|
597 | } |
---|
598 | |
---|
599 | void LinkReferenceToTypes::postvisit( TypeInstType *typeInst ) { |
---|
600 | // ensure generic parameter instances are renamed like the base type |
---|
601 | if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name; |
---|
602 | if ( NamedTypeDecl *namedTypeDecl = local_indexer->lookupType( typeInst->get_name() ) ) { |
---|
603 | if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) { |
---|
604 | typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype ); |
---|
605 | } // if |
---|
606 | } // if |
---|
607 | } |
---|
608 | |
---|
609 | /// Fix up assertions - flattens assertion lists, removing all trait instances |
---|
610 | void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) { |
---|
611 | for ( TypeDecl * type : forall ) { |
---|
612 | std::list< DeclarationWithType * > asserts; |
---|
613 | asserts.splice( asserts.end(), type->assertions ); |
---|
614 | // expand trait instances into their members |
---|
615 | for ( DeclarationWithType * assertion : asserts ) { |
---|
616 | if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) { |
---|
617 | // expand trait instance into all of its members |
---|
618 | expandAssertions( traitInst, back_inserter( type->assertions ) ); |
---|
619 | delete traitInst; |
---|
620 | } else { |
---|
621 | // pass other assertions through |
---|
622 | type->assertions.push_back( assertion ); |
---|
623 | } // if |
---|
624 | } // for |
---|
625 | // apply FixFunction to every assertion to check for invalid void type |
---|
626 | for ( DeclarationWithType *& assertion : type->assertions ) { |
---|
627 | bool isVoid = fixFunction( assertion ); |
---|
628 | if ( isVoid ) { |
---|
629 | SemanticError( node, "invalid type void in assertion of function " ); |
---|
630 | } // if |
---|
631 | } // for |
---|
632 | // normalizeAssertions( type->assertions ); |
---|
633 | } // for |
---|
634 | } |
---|
635 | |
---|
636 | void ForallPointerDecay::previsit( ObjectDecl *object ) { |
---|
637 | // ensure that operator names only apply to functions or function pointers |
---|
638 | if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) { |
---|
639 | SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) ); |
---|
640 | } |
---|
641 | object->fixUniqueId(); |
---|
642 | } |
---|
643 | |
---|
644 | void ForallPointerDecay::previsit( FunctionDecl *func ) { |
---|
645 | func->fixUniqueId(); |
---|
646 | } |
---|
647 | |
---|
648 | void ForallPointerDecay::previsit( FunctionType * ftype ) { |
---|
649 | forallFixer( ftype->forall, ftype ); |
---|
650 | } |
---|
651 | |
---|
652 | void ForallPointerDecay::previsit( StructDecl * aggrDecl ) { |
---|
653 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
654 | } |
---|
655 | |
---|
656 | void ForallPointerDecay::previsit( UnionDecl * aggrDecl ) { |
---|
657 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
658 | } |
---|
659 | |
---|
660 | void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) { |
---|
661 | PassVisitor<ReturnChecker> checker; |
---|
662 | acceptAll( translationUnit, checker ); |
---|
663 | } |
---|
664 | |
---|
665 | void ReturnChecker::previsit( FunctionDecl * functionDecl ) { |
---|
666 | GuardValue( returnVals ); |
---|
667 | returnVals = functionDecl->get_functionType()->get_returnVals(); |
---|
668 | } |
---|
669 | |
---|
670 | void ReturnChecker::previsit( ReturnStmt * returnStmt ) { |
---|
671 | // Previously this also checked for the existence of an expr paired with no return values on |
---|
672 | // the function return type. This is incorrect, since you can have an expression attached to |
---|
673 | // a return statement in a void-returning function in C. The expression is treated as if it |
---|
674 | // were cast to void. |
---|
675 | if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) { |
---|
676 | SemanticError( returnStmt, "Non-void function returns no values: " ); |
---|
677 | } |
---|
678 | } |
---|
679 | |
---|
680 | |
---|
681 | bool isTypedef( Declaration *decl ) { |
---|
682 | return dynamic_cast< TypedefDecl * >( decl ); |
---|
683 | } |
---|
684 | |
---|
685 | void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) { |
---|
686 | PassVisitor<EliminateTypedef> eliminator; |
---|
687 | mutateAll( translationUnit, eliminator ); |
---|
688 | if ( eliminator.pass.typedefNames.count( "size_t" ) ) { |
---|
689 | // grab and remember declaration of size_t |
---|
690 | SizeType = eliminator.pass.typedefNames["size_t"].first->get_base()->clone(); |
---|
691 | } else { |
---|
692 | // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong |
---|
693 | // eventually should have a warning for this case. |
---|
694 | SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ); |
---|
695 | } |
---|
696 | filter( translationUnit, isTypedef, true ); |
---|
697 | } |
---|
698 | |
---|
699 | Type * EliminateTypedef::postmutate( TypeInstType * typeInst ) { |
---|
700 | // instances of typedef types will come here. If it is an instance |
---|
701 | // of a typdef type, link the instance to its actual type. |
---|
702 | TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() ); |
---|
703 | if ( def != typedefNames.end() ) { |
---|
704 | Type *ret = def->second.first->base->clone(); |
---|
705 | ret->get_qualifiers() |= typeInst->get_qualifiers(); |
---|
706 | // attributes are not carried over from typedef to function parameters/return values |
---|
707 | if ( ! inFunctionType ) { |
---|
708 | ret->attributes.splice( ret->attributes.end(), typeInst->attributes ); |
---|
709 | } else { |
---|
710 | deleteAll( ret->attributes ); |
---|
711 | ret->attributes.clear(); |
---|
712 | } |
---|
713 | // place instance parameters on the typedef'd type |
---|
714 | if ( ! typeInst->parameters.empty() ) { |
---|
715 | ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret); |
---|
716 | if ( ! rtt ) { |
---|
717 | SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name ); |
---|
718 | } |
---|
719 | rtt->get_parameters().clear(); |
---|
720 | cloneAll( typeInst->parameters, rtt->parameters ); |
---|
721 | mutateAll( rtt->parameters, *visitor ); // recursively fix typedefs on parameters |
---|
722 | } // if |
---|
723 | delete typeInst; |
---|
724 | return ret; |
---|
725 | } else { |
---|
726 | TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() ); |
---|
727 | assertf( base != typedeclNames.end(), "Cannot find typedecl name %s", typeInst->name.c_str() ); |
---|
728 | typeInst->set_baseType( base->second ); |
---|
729 | } // if |
---|
730 | return typeInst; |
---|
731 | } |
---|
732 | |
---|
733 | struct VarLenChecker : WithShortCircuiting { |
---|
734 | void previsit( FunctionType * ) { visit_children = false; } |
---|
735 | void previsit( ArrayType * at ) { |
---|
736 | isVarLen |= at->isVarLen; |
---|
737 | } |
---|
738 | bool isVarLen = false; |
---|
739 | }; |
---|
740 | |
---|
741 | bool isVariableLength( Type * t ) { |
---|
742 | PassVisitor<VarLenChecker> varLenChecker; |
---|
743 | maybeAccept( t, varLenChecker ); |
---|
744 | return varLenChecker.pass.isVarLen; |
---|
745 | } |
---|
746 | |
---|
747 | Declaration *EliminateTypedef::postmutate( TypedefDecl * tyDecl ) { |
---|
748 | if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) { |
---|
749 | // typedef to the same name from the same scope |
---|
750 | // must be from the same type |
---|
751 | |
---|
752 | Type * t1 = tyDecl->get_base(); |
---|
753 | Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base(); |
---|
754 | if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) { |
---|
755 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
756 | } |
---|
757 | // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs |
---|
758 | // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs |
---|
759 | // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required |
---|
760 | // to fix this corner case likely outweighs the utility of allowing it. |
---|
761 | if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) { |
---|
762 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
763 | } |
---|
764 | } else { |
---|
765 | typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel ); |
---|
766 | } // if |
---|
767 | |
---|
768 | // When a typedef is a forward declaration: |
---|
769 | // typedef struct screen SCREEN; |
---|
770 | // the declaration portion must be retained: |
---|
771 | // struct screen; |
---|
772 | // because the expansion of the typedef is: |
---|
773 | // void rtn( SCREEN *p ) => void rtn( struct screen *p ) |
---|
774 | // hence the type-name "screen" must be defined. |
---|
775 | // Note, qualifiers on the typedef are superfluous for the forward declaration. |
---|
776 | |
---|
777 | Type *designatorType = tyDecl->get_base()->stripDeclarator(); |
---|
778 | if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) { |
---|
779 | return new StructDecl( aggDecl->get_name(), DeclarationNode::Struct, noAttributes, tyDecl->get_linkage() ); |
---|
780 | } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) { |
---|
781 | return new UnionDecl( aggDecl->get_name(), noAttributes, tyDecl->get_linkage() ); |
---|
782 | } else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) { |
---|
783 | return new EnumDecl( enumDecl->get_name(), noAttributes, tyDecl->get_linkage() ); |
---|
784 | } else { |
---|
785 | return tyDecl->clone(); |
---|
786 | } // if |
---|
787 | } |
---|
788 | |
---|
789 | void EliminateTypedef::premutate( TypeDecl * typeDecl ) { |
---|
790 | TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() ); |
---|
791 | if ( i != typedefNames.end() ) { |
---|
792 | typedefNames.erase( i ) ; |
---|
793 | } // if |
---|
794 | |
---|
795 | typedeclNames[ typeDecl->get_name() ] = typeDecl; |
---|
796 | } |
---|
797 | |
---|
798 | void EliminateTypedef::premutate( FunctionDecl * ) { |
---|
799 | GuardScope( typedefNames ); |
---|
800 | } |
---|
801 | |
---|
802 | void EliminateTypedef::premutate( ObjectDecl * ) { |
---|
803 | GuardScope( typedefNames ); |
---|
804 | } |
---|
805 | |
---|
806 | DeclarationWithType *EliminateTypedef::postmutate( ObjectDecl * objDecl ) { |
---|
807 | if ( FunctionType *funtype = dynamic_cast<FunctionType *>( objDecl->get_type() ) ) { // function type? |
---|
808 | // replace the current object declaration with a function declaration |
---|
809 | FunctionDecl * newDecl = new FunctionDecl( objDecl->get_name(), objDecl->get_storageClasses(), objDecl->get_linkage(), funtype, 0, objDecl->get_attributes(), objDecl->get_funcSpec() ); |
---|
810 | objDecl->get_attributes().clear(); |
---|
811 | objDecl->set_type( nullptr ); |
---|
812 | delete objDecl; |
---|
813 | return newDecl; |
---|
814 | } // if |
---|
815 | return objDecl; |
---|
816 | } |
---|
817 | |
---|
818 | void EliminateTypedef::premutate( CastExpr * ) { |
---|
819 | GuardScope( typedefNames ); |
---|
820 | } |
---|
821 | |
---|
822 | void EliminateTypedef::premutate( CompoundStmt * ) { |
---|
823 | GuardScope( typedefNames ); |
---|
824 | scopeLevel += 1; |
---|
825 | GuardAction( [this](){ scopeLevel -= 1; } ); |
---|
826 | } |
---|
827 | |
---|
828 | CompoundStmt *EliminateTypedef::postmutate( CompoundStmt * compoundStmt ) { |
---|
829 | // remove and delete decl stmts |
---|
830 | filter( compoundStmt->kids, [](Statement * stmt) { |
---|
831 | if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( stmt ) ) { |
---|
832 | if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) { |
---|
833 | return true; |
---|
834 | } // if |
---|
835 | } // if |
---|
836 | return false; |
---|
837 | }, true); |
---|
838 | return compoundStmt; |
---|
839 | } |
---|
840 | |
---|
841 | // there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed |
---|
842 | // as well |
---|
843 | template<typename AggDecl> |
---|
844 | AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) { |
---|
845 | filter( aggDecl->members, isTypedef, true ); |
---|
846 | return aggDecl; |
---|
847 | } |
---|
848 | |
---|
849 | template<typename AggDecl> |
---|
850 | void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) { |
---|
851 | if ( typedefNames.count( aggDecl->get_name() ) == 0 ) { |
---|
852 | Type *type = nullptr; |
---|
853 | if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) { |
---|
854 | type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ); |
---|
855 | } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) { |
---|
856 | type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ); |
---|
857 | } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) { |
---|
858 | type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ); |
---|
859 | } // if |
---|
860 | TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) ); |
---|
861 | typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel ); |
---|
862 | } // if |
---|
863 | } |
---|
864 | |
---|
865 | void EliminateTypedef::premutate( StructDecl * structDecl ) { |
---|
866 | addImplicitTypedef( structDecl ); |
---|
867 | } |
---|
868 | |
---|
869 | |
---|
870 | Declaration *EliminateTypedef::postmutate( StructDecl * structDecl ) { |
---|
871 | return handleAggregate( structDecl ); |
---|
872 | } |
---|
873 | |
---|
874 | void EliminateTypedef::premutate( UnionDecl * unionDecl ) { |
---|
875 | addImplicitTypedef( unionDecl ); |
---|
876 | } |
---|
877 | |
---|
878 | Declaration *EliminateTypedef::postmutate( UnionDecl * unionDecl ) { |
---|
879 | return handleAggregate( unionDecl ); |
---|
880 | } |
---|
881 | |
---|
882 | void EliminateTypedef::premutate( EnumDecl * enumDecl ) { |
---|
883 | addImplicitTypedef( enumDecl ); |
---|
884 | } |
---|
885 | |
---|
886 | Declaration *EliminateTypedef::postmutate( EnumDecl * enumDecl ) { |
---|
887 | return handleAggregate( enumDecl ); |
---|
888 | } |
---|
889 | |
---|
890 | Declaration *EliminateTypedef::postmutate( TraitDecl * traitDecl ) { |
---|
891 | return handleAggregate( traitDecl ); |
---|
892 | } |
---|
893 | |
---|
894 | void EliminateTypedef::premutate( FunctionType * ) { |
---|
895 | GuardValue( inFunctionType ); |
---|
896 | inFunctionType = true; |
---|
897 | } |
---|
898 | |
---|
899 | void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) { |
---|
900 | PassVisitor<VerifyCtorDtorAssign> verifier; |
---|
901 | acceptAll( translationUnit, verifier ); |
---|
902 | } |
---|
903 | |
---|
904 | void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) { |
---|
905 | FunctionType * funcType = funcDecl->get_functionType(); |
---|
906 | std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals(); |
---|
907 | std::list< DeclarationWithType * > ¶ms = funcType->get_parameters(); |
---|
908 | |
---|
909 | if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc. |
---|
910 | if ( params.size() == 0 ) { |
---|
911 | SemanticError( funcDecl, "Constructors, destructors, and assignment functions require at least one parameter " ); |
---|
912 | } |
---|
913 | ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() ); |
---|
914 | if ( ! refType ) { |
---|
915 | SemanticError( funcDecl, "First parameter of a constructor, destructor, or assignment function must be a reference " ); |
---|
916 | } |
---|
917 | if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) { |
---|
918 | SemanticError( funcDecl, "Constructors and destructors cannot have explicit return values " ); |
---|
919 | } |
---|
920 | } |
---|
921 | } |
---|
922 | |
---|
923 | template< typename Aggr > |
---|
924 | void validateGeneric( Aggr * inst ) { |
---|
925 | std::list< TypeDecl * > * params = inst->get_baseParameters(); |
---|
926 | if ( params ) { |
---|
927 | std::list< Expression * > & args = inst->get_parameters(); |
---|
928 | |
---|
929 | // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list). |
---|
930 | // A substitution is used to ensure that defaults are replaced correctly, e.g., |
---|
931 | // forall(otype T, otype alloc = heap_allocator(T)) struct vector; |
---|
932 | // vector(int) v; |
---|
933 | // after insertion of default values becomes |
---|
934 | // vector(int, heap_allocator(T)) |
---|
935 | // and the substitution is built with T=int so that after substitution, the result is |
---|
936 | // vector(int, heap_allocator(int)) |
---|
937 | TypeSubstitution sub; |
---|
938 | auto paramIter = params->begin(); |
---|
939 | for ( size_t i = 0; paramIter != params->end(); ++paramIter, ++i ) { |
---|
940 | if ( i < args.size() ) { |
---|
941 | TypeExpr * expr = strict_dynamic_cast< TypeExpr * >( *std::next( args.begin(), i ) ); |
---|
942 | sub.add( (*paramIter)->get_name(), expr->get_type()->clone() ); |
---|
943 | } else if ( i == args.size() ) { |
---|
944 | Type * defaultType = (*paramIter)->get_init(); |
---|
945 | if ( defaultType ) { |
---|
946 | args.push_back( new TypeExpr( defaultType->clone() ) ); |
---|
947 | sub.add( (*paramIter)->get_name(), defaultType->clone() ); |
---|
948 | } |
---|
949 | } |
---|
950 | } |
---|
951 | |
---|
952 | sub.apply( inst ); |
---|
953 | if ( args.size() < params->size() ) SemanticError( inst, "Too few type arguments in generic type " ); |
---|
954 | if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " ); |
---|
955 | } |
---|
956 | } |
---|
957 | |
---|
958 | void ValidateGenericParameters::previsit( StructInstType * inst ) { |
---|
959 | validateGeneric( inst ); |
---|
960 | } |
---|
961 | |
---|
962 | void ValidateGenericParameters::previsit( UnionInstType * inst ) { |
---|
963 | validateGeneric( inst ); |
---|
964 | } |
---|
965 | |
---|
966 | void CompoundLiteral::premutate( ObjectDecl *objectDecl ) { |
---|
967 | storageClasses = objectDecl->get_storageClasses(); |
---|
968 | } |
---|
969 | |
---|
970 | Expression *CompoundLiteral::postmutate( CompoundLiteralExpr *compLitExpr ) { |
---|
971 | // transform [storage_class] ... (struct S){ 3, ... }; |
---|
972 | // into [storage_class] struct S temp = { 3, ... }; |
---|
973 | static UniqueName indexName( "_compLit" ); |
---|
974 | |
---|
975 | ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() ); |
---|
976 | compLitExpr->set_result( nullptr ); |
---|
977 | compLitExpr->set_initializer( nullptr ); |
---|
978 | delete compLitExpr; |
---|
979 | declsToAddBefore.push_back( tempvar ); // add modified temporary to current block |
---|
980 | return new VariableExpr( tempvar ); |
---|
981 | } |
---|
982 | |
---|
983 | void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) { |
---|
984 | PassVisitor<ReturnTypeFixer> fixer; |
---|
985 | acceptAll( translationUnit, fixer ); |
---|
986 | } |
---|
987 | |
---|
988 | void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) { |
---|
989 | FunctionType * ftype = functionDecl->get_functionType(); |
---|
990 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
991 | assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() ); |
---|
992 | if ( retVals.size() == 1 ) { |
---|
993 | // ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging). |
---|
994 | // ensure other return values have a name. |
---|
995 | DeclarationWithType * ret = retVals.front(); |
---|
996 | if ( ret->get_name() == "" ) { |
---|
997 | ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) ); |
---|
998 | } |
---|
999 | ret->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
1000 | } |
---|
1001 | } |
---|
1002 | |
---|
1003 | void ReturnTypeFixer::postvisit( FunctionType * ftype ) { |
---|
1004 | // xxx - need to handle named return values - this information needs to be saved somehow |
---|
1005 | // so that resolution has access to the names. |
---|
1006 | // Note that this pass needs to happen early so that other passes which look for tuple types |
---|
1007 | // find them in all of the right places, including function return types. |
---|
1008 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
1009 | if ( retVals.size() > 1 ) { |
---|
1010 | // generate a single return parameter which is the tuple of all of the return values |
---|
1011 | TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) ); |
---|
1012 | // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false. |
---|
1013 | ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) ); |
---|
1014 | deleteAll( retVals ); |
---|
1015 | retVals.clear(); |
---|
1016 | retVals.push_back( newRet ); |
---|
1017 | } |
---|
1018 | } |
---|
1019 | |
---|
1020 | void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) { |
---|
1021 | PassVisitor<ArrayLength> len; |
---|
1022 | acceptAll( translationUnit, len ); |
---|
1023 | } |
---|
1024 | |
---|
1025 | void ArrayLength::previsit( ObjectDecl * objDecl ) { |
---|
1026 | if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) { |
---|
1027 | if ( at->get_dimension() ) return; |
---|
1028 | if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) { |
---|
1029 | at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) ); |
---|
1030 | } |
---|
1031 | } |
---|
1032 | } |
---|
1033 | |
---|
1034 | struct LabelFinder { |
---|
1035 | std::set< Label > & labels; |
---|
1036 | LabelFinder( std::set< Label > & labels ) : labels( labels ) {} |
---|
1037 | void previsit( Statement * stmt ) { |
---|
1038 | for ( Label & l : stmt->labels ) { |
---|
1039 | labels.insert( l ); |
---|
1040 | } |
---|
1041 | } |
---|
1042 | }; |
---|
1043 | |
---|
1044 | void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) { |
---|
1045 | GuardValue( labels ); |
---|
1046 | PassVisitor<LabelFinder> finder( labels ); |
---|
1047 | funcDecl->accept( finder ); |
---|
1048 | } |
---|
1049 | |
---|
1050 | Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) { |
---|
1051 | // convert &&label into label address |
---|
1052 | if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) { |
---|
1053 | if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) { |
---|
1054 | if ( labels.count( nameExpr->name ) ) { |
---|
1055 | Label name = nameExpr->name; |
---|
1056 | delete addrExpr; |
---|
1057 | return new LabelAddressExpr( name ); |
---|
1058 | } |
---|
1059 | } |
---|
1060 | } |
---|
1061 | return addrExpr; |
---|
1062 | } |
---|
1063 | |
---|
1064 | void FindSpecialDeclarations::previsit( FunctionDecl * funcDecl ) { |
---|
1065 | if ( ! dereferenceOperator ) { |
---|
1066 | if ( funcDecl->get_name() == "*?" && funcDecl->get_linkage() == LinkageSpec::Intrinsic ) { |
---|
1067 | FunctionType * ftype = funcDecl->get_functionType(); |
---|
1068 | if ( ftype->get_parameters().size() == 1 && ftype->get_parameters().front()->get_type()->get_qualifiers() == Type::Qualifiers() ) { |
---|
1069 | dereferenceOperator = funcDecl; |
---|
1070 | } |
---|
1071 | } |
---|
1072 | } |
---|
1073 | } |
---|
1074 | } // namespace SymTab |
---|
1075 | |
---|
1076 | // Local Variables: // |
---|
1077 | // tab-width: 4 // |
---|
1078 | // mode: c++ // |
---|
1079 | // compile-command: "make install" // |
---|
1080 | // End: // |
---|