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 : Andrew Beach |
---|
12 | // Last Modified On : Tue Jul 12 15:00:00 2022 |
---|
13 | // Update Count : 367 |
---|
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 <unordered_map> // for unordered_map |
---|
47 | #include <utility> // for pair |
---|
48 | |
---|
49 | #include "CodeGen/CodeGenerator.h" // for genName |
---|
50 | #include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign |
---|
51 | #include "ControlStruct/Mutate.h" // for ForExprMutator |
---|
52 | #include "Common/CodeLocation.h" // for CodeLocation |
---|
53 | #include "Common/Stats.h" // for Stats::Heap |
---|
54 | #include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd |
---|
55 | #include "Common/ScopedMap.h" // for ScopedMap |
---|
56 | #include "Common/SemanticError.h" // for SemanticError |
---|
57 | #include "Common/ToString.hpp" // for toCString |
---|
58 | #include "Common/UniqueName.h" // for UniqueName |
---|
59 | #include "Common/utility.h" // for cloneAll, deleteAll |
---|
60 | #include "CompilationState.h" // skip some passes in new-ast build |
---|
61 | #include "Concurrency/Keywords.h" // for applyKeywords |
---|
62 | #include "FixFunction.h" // for FixFunction |
---|
63 | #include "Indexer.h" // for Indexer |
---|
64 | #include "InitTweak/GenInit.h" // for fixReturnStatements |
---|
65 | #include "InitTweak/InitTweak.h" // for isCtorDtorAssign |
---|
66 | #include "ResolvExpr/typeops.h" // for extractResultType |
---|
67 | #include "ResolvExpr/Unify.h" // for typesCompatible |
---|
68 | #include "ResolvExpr/Resolver.h" // for findSingleExpression |
---|
69 | #include "ResolvExpr/ResolveTypeof.h" // for resolveTypeof |
---|
70 | #include "SymTab/Autogen.h" // for SizeType |
---|
71 | #include "SymTab/ValidateType.h" // for decayEnumsAndPointers, decayFo... |
---|
72 | #include "SynTree/LinkageSpec.h" // for C |
---|
73 | #include "SynTree/Attribute.h" // for noAttributes, Attribute |
---|
74 | #include "SynTree/Constant.h" // for Constant |
---|
75 | #include "SynTree/Declaration.h" // for ObjectDecl, DeclarationWithType |
---|
76 | #include "SynTree/Expression.h" // for CompoundLiteralExpr, Expressio... |
---|
77 | #include "SynTree/Initializer.h" // for ListInit, Initializer |
---|
78 | #include "SynTree/Label.h" // for operator==, Label |
---|
79 | #include "SynTree/Mutator.h" // for Mutator |
---|
80 | #include "SynTree/Type.h" // for Type, TypeInstType, EnumInstType |
---|
81 | #include "SynTree/TypeSubstitution.h" // for TypeSubstitution |
---|
82 | #include "SynTree/Visitor.h" // for Visitor |
---|
83 | #include "Validate/HandleAttributes.h" // for handleAttributes |
---|
84 | #include "Validate/FindSpecialDecls.h" // for FindSpecialDecls |
---|
85 | |
---|
86 | class CompoundStmt; |
---|
87 | class ReturnStmt; |
---|
88 | class SwitchStmt; |
---|
89 | |
---|
90 | #define debugPrint( x ) if ( doDebug ) x |
---|
91 | |
---|
92 | namespace SymTab { |
---|
93 | /// hoists declarations that are difficult to hoist while parsing |
---|
94 | struct HoistTypeDecls final : public WithDeclsToAdd { |
---|
95 | void previsit( SizeofExpr * ); |
---|
96 | void previsit( AlignofExpr * ); |
---|
97 | void previsit( UntypedOffsetofExpr * ); |
---|
98 | void previsit( CompoundLiteralExpr * ); |
---|
99 | void handleType( Type * ); |
---|
100 | }; |
---|
101 | |
---|
102 | struct FixQualifiedTypes final : public WithIndexer { |
---|
103 | FixQualifiedTypes() : WithIndexer(false) {} |
---|
104 | Type * postmutate( QualifiedType * ); |
---|
105 | }; |
---|
106 | |
---|
107 | struct HoistStruct final : public WithDeclsToAdd, public WithGuards { |
---|
108 | /// Flattens nested struct types |
---|
109 | static void hoistStruct( std::list< Declaration * > &translationUnit ); |
---|
110 | |
---|
111 | void previsit( StructDecl * aggregateDecl ); |
---|
112 | void previsit( UnionDecl * aggregateDecl ); |
---|
113 | void previsit( StaticAssertDecl * assertDecl ); |
---|
114 | void previsit( StructInstType * type ); |
---|
115 | void previsit( UnionInstType * type ); |
---|
116 | void previsit( EnumInstType * type ); |
---|
117 | |
---|
118 | private: |
---|
119 | template< typename AggDecl > void handleAggregate( AggDecl * aggregateDecl ); |
---|
120 | |
---|
121 | AggregateDecl * parentAggr = nullptr; |
---|
122 | }; |
---|
123 | |
---|
124 | /// Fix return types so that every function returns exactly one value |
---|
125 | struct ReturnTypeFixer { |
---|
126 | static void fix( std::list< Declaration * > &translationUnit ); |
---|
127 | |
---|
128 | void postvisit( FunctionDecl * functionDecl ); |
---|
129 | void postvisit( FunctionType * ftype ); |
---|
130 | }; |
---|
131 | |
---|
132 | /// Does early resolution on the expressions that give enumeration constants their values |
---|
133 | struct ResolveEnumInitializers final : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveEnumInitializers>, public WithShortCircuiting { |
---|
134 | ResolveEnumInitializers( const Indexer * indexer ); |
---|
135 | void postvisit( EnumDecl * enumDecl ); |
---|
136 | |
---|
137 | private: |
---|
138 | const Indexer * local_indexer; |
---|
139 | |
---|
140 | }; |
---|
141 | |
---|
142 | /// Replaces array and function types in forall lists by appropriate pointer type and assigns each Object and Function declaration a unique ID. |
---|
143 | struct ForallPointerDecay_old final { |
---|
144 | void previsit( ObjectDecl * object ); |
---|
145 | void previsit( FunctionDecl * func ); |
---|
146 | void previsit( FunctionType * ftype ); |
---|
147 | void previsit( StructDecl * aggrDecl ); |
---|
148 | void previsit( UnionDecl * aggrDecl ); |
---|
149 | }; |
---|
150 | |
---|
151 | struct ReturnChecker : public WithGuards { |
---|
152 | /// Checks that return statements return nothing if their return type is void |
---|
153 | /// and return something if the return type is non-void. |
---|
154 | static void checkFunctionReturns( std::list< Declaration * > & translationUnit ); |
---|
155 | |
---|
156 | void previsit( FunctionDecl * functionDecl ); |
---|
157 | void previsit( ReturnStmt * returnStmt ); |
---|
158 | |
---|
159 | typedef std::list< DeclarationWithType * > ReturnVals; |
---|
160 | ReturnVals returnVals; |
---|
161 | }; |
---|
162 | |
---|
163 | struct ReplaceTypedef final : public WithVisitorRef<ReplaceTypedef>, public WithGuards, public WithShortCircuiting, public WithDeclsToAdd { |
---|
164 | ReplaceTypedef() : scopeLevel( 0 ) {} |
---|
165 | /// Replaces typedefs by forward declarations |
---|
166 | static void replaceTypedef( std::list< Declaration * > &translationUnit ); |
---|
167 | |
---|
168 | void premutate( QualifiedType * ); |
---|
169 | Type * postmutate( QualifiedType * qualType ); |
---|
170 | Type * postmutate( TypeInstType * aggregateUseType ); |
---|
171 | Declaration * postmutate( TypedefDecl * typeDecl ); |
---|
172 | void premutate( TypeDecl * typeDecl ); |
---|
173 | void premutate( FunctionDecl * funcDecl ); |
---|
174 | void premutate( ObjectDecl * objDecl ); |
---|
175 | DeclarationWithType * postmutate( ObjectDecl * objDecl ); |
---|
176 | |
---|
177 | void premutate( CastExpr * castExpr ); |
---|
178 | |
---|
179 | void premutate( CompoundStmt * compoundStmt ); |
---|
180 | |
---|
181 | void premutate( StructDecl * structDecl ); |
---|
182 | void premutate( UnionDecl * unionDecl ); |
---|
183 | void premutate( EnumDecl * enumDecl ); |
---|
184 | void premutate( TraitDecl * ); |
---|
185 | |
---|
186 | void premutate( FunctionType * ftype ); |
---|
187 | |
---|
188 | private: |
---|
189 | template<typename AggDecl> |
---|
190 | void addImplicitTypedef( AggDecl * aggDecl ); |
---|
191 | template< typename AggDecl > |
---|
192 | void handleAggregate( AggDecl * aggr ); |
---|
193 | |
---|
194 | typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr; |
---|
195 | typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap; |
---|
196 | typedef ScopedMap< std::string, TypeDecl * > TypeDeclMap; |
---|
197 | TypedefMap typedefNames; |
---|
198 | TypeDeclMap typedeclNames; |
---|
199 | int scopeLevel; |
---|
200 | bool inFunctionType = false; |
---|
201 | }; |
---|
202 | |
---|
203 | struct EliminateTypedef { |
---|
204 | /// removes TypedefDecls from the AST |
---|
205 | static void eliminateTypedef( std::list< Declaration * > &translationUnit ); |
---|
206 | |
---|
207 | template<typename AggDecl> |
---|
208 | void handleAggregate( AggDecl * aggregateDecl ); |
---|
209 | |
---|
210 | void previsit( StructDecl * aggregateDecl ); |
---|
211 | void previsit( UnionDecl * aggregateDecl ); |
---|
212 | void previsit( CompoundStmt * compoundStmt ); |
---|
213 | }; |
---|
214 | |
---|
215 | struct VerifyCtorDtorAssign { |
---|
216 | /// ensure that constructors, destructors, and assignment have at least one |
---|
217 | /// parameter, the first of which must be a pointer, and that ctor/dtors have no |
---|
218 | /// return values. |
---|
219 | static void verify( std::list< Declaration * > &translationUnit ); |
---|
220 | |
---|
221 | void previsit( FunctionDecl * funcDecl ); |
---|
222 | }; |
---|
223 | |
---|
224 | /// ensure that generic types have the correct number of type arguments |
---|
225 | struct ValidateGenericParameters { |
---|
226 | void previsit( StructInstType * inst ); |
---|
227 | void previsit( UnionInstType * inst ); |
---|
228 | }; |
---|
229 | |
---|
230 | /// desugar declarations and uses of dimension paramaters like [N], |
---|
231 | /// from type-system managed values, to tunnneling via ordinary types, |
---|
232 | /// as char[-] in and sizeof(-) out |
---|
233 | struct TranslateDimensionGenericParameters : public WithIndexer, public WithGuards { |
---|
234 | static void translateDimensions( std::list< Declaration * > &translationUnit ); |
---|
235 | TranslateDimensionGenericParameters(); |
---|
236 | |
---|
237 | bool nextVisitedNodeIsChildOfSUIT = false; // SUIT = Struct or Union -Inst Type |
---|
238 | bool visitingChildOfSUIT = false; |
---|
239 | void changeState_ChildOfSUIT( bool newVal ); |
---|
240 | void premutate( StructInstType * sit ); |
---|
241 | void premutate( UnionInstType * uit ); |
---|
242 | void premutate( BaseSyntaxNode * node ); |
---|
243 | |
---|
244 | TypeDecl * postmutate( TypeDecl * td ); |
---|
245 | Expression * postmutate( DimensionExpr * de ); |
---|
246 | Expression * postmutate( Expression * e ); |
---|
247 | }; |
---|
248 | |
---|
249 | struct FixObjectType : public WithIndexer { |
---|
250 | /// resolves typeof type in object, function, and type declarations |
---|
251 | static void fix( std::list< Declaration * > & translationUnit ); |
---|
252 | |
---|
253 | void previsit( ObjectDecl * ); |
---|
254 | void previsit( FunctionDecl * ); |
---|
255 | void previsit( TypeDecl * ); |
---|
256 | }; |
---|
257 | |
---|
258 | struct InitializerLength { |
---|
259 | /// for array types without an explicit length, compute the length and store it so that it |
---|
260 | /// is known to the rest of the phases. For example, |
---|
261 | /// int x[] = { 1, 2, 3 }; |
---|
262 | /// int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
263 | /// here x and y are known at compile-time to have length 3, so change this into |
---|
264 | /// int x[3] = { 1, 2, 3 }; |
---|
265 | /// int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } }; |
---|
266 | static void computeLength( std::list< Declaration * > & translationUnit ); |
---|
267 | |
---|
268 | void previsit( ObjectDecl * objDecl ); |
---|
269 | }; |
---|
270 | |
---|
271 | struct ArrayLength : public WithIndexer { |
---|
272 | static void computeLength( std::list< Declaration * > & translationUnit ); |
---|
273 | |
---|
274 | void previsit( ArrayType * arrayType ); |
---|
275 | }; |
---|
276 | |
---|
277 | struct CompoundLiteral final : public WithDeclsToAdd, public WithVisitorRef<CompoundLiteral> { |
---|
278 | Type::StorageClasses storageClasses; |
---|
279 | |
---|
280 | void premutate( ObjectDecl * objectDecl ); |
---|
281 | Expression * postmutate( CompoundLiteralExpr * compLitExpr ); |
---|
282 | }; |
---|
283 | |
---|
284 | struct LabelAddressFixer final : public WithGuards { |
---|
285 | std::set< Label > labels; |
---|
286 | |
---|
287 | void premutate( FunctionDecl * funcDecl ); |
---|
288 | Expression * postmutate( AddressExpr * addrExpr ); |
---|
289 | }; |
---|
290 | |
---|
291 | void validate( std::list< Declaration * > &translationUnit, __attribute__((unused)) bool doDebug ) { |
---|
292 | PassVisitor<HoistTypeDecls> hoistDecls; |
---|
293 | { |
---|
294 | Stats::Heap::newPass("validate-A"); |
---|
295 | Stats::Time::BlockGuard guard("validate-A"); |
---|
296 | VerifyCtorDtorAssign::verify( translationUnit ); // must happen before autogen, because autogen examines existing ctor/dtors |
---|
297 | acceptAll( translationUnit, hoistDecls ); |
---|
298 | ReplaceTypedef::replaceTypedef( translationUnit ); |
---|
299 | ReturnTypeFixer::fix( translationUnit ); // must happen before autogen |
---|
300 | decayEnumsAndPointers( translationUnit ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist; before LinkReferenceToTypes_old because it is an indexer and needs correct types for mangling |
---|
301 | } |
---|
302 | PassVisitor<FixQualifiedTypes> fixQual; |
---|
303 | { |
---|
304 | Stats::Heap::newPass("validate-B"); |
---|
305 | Stats::Time::BlockGuard guard("validate-B"); |
---|
306 | linkReferenceToTypes( translationUnit ); // Must happen before auto-gen, because it uses the sized flag. |
---|
307 | mutateAll( translationUnit, fixQual ); // must happen after LinkReferenceToTypes_old, because aggregate members are accessed |
---|
308 | HoistStruct::hoistStruct( translationUnit ); |
---|
309 | EliminateTypedef::eliminateTypedef( translationUnit ); |
---|
310 | } |
---|
311 | PassVisitor<ValidateGenericParameters> genericParams; |
---|
312 | PassVisitor<ResolveEnumInitializers> rei( nullptr ); |
---|
313 | { |
---|
314 | Stats::Heap::newPass("validate-C"); |
---|
315 | Stats::Time::BlockGuard guard("validate-C"); |
---|
316 | Stats::Time::TimeBlock("Validate Generic Parameters", [&]() { |
---|
317 | acceptAll( translationUnit, genericParams ); // check as early as possible - can't happen before LinkReferenceToTypes_old; observed failing when attempted before eliminateTypedef |
---|
318 | }); |
---|
319 | Stats::Time::TimeBlock("Translate Dimensions", [&]() { |
---|
320 | TranslateDimensionGenericParameters::translateDimensions( translationUnit ); |
---|
321 | }); |
---|
322 | if (!useNewAST) { |
---|
323 | Stats::Time::TimeBlock("Resolve Enum Initializers", [&]() { |
---|
324 | acceptAll( translationUnit, rei ); // must happen after translateDimensions because rei needs identifier lookup, which needs name mangling |
---|
325 | }); |
---|
326 | } |
---|
327 | Stats::Time::TimeBlock("Check Function Returns", [&]() { |
---|
328 | ReturnChecker::checkFunctionReturns( translationUnit ); |
---|
329 | }); |
---|
330 | Stats::Time::TimeBlock("Fix Return Statements", [&]() { |
---|
331 | InitTweak::fixReturnStatements( translationUnit ); // must happen before autogen |
---|
332 | }); |
---|
333 | } |
---|
334 | { |
---|
335 | Stats::Heap::newPass("validate-D"); |
---|
336 | Stats::Time::BlockGuard guard("validate-D"); |
---|
337 | Stats::Time::TimeBlock("Apply Concurrent Keywords", [&]() { |
---|
338 | Concurrency::applyKeywords( translationUnit ); |
---|
339 | }); |
---|
340 | Stats::Time::TimeBlock("Forall Pointer Decay", [&]() { |
---|
341 | decayForallPointers( translationUnit ); // must happen before autogenerateRoutines, after Concurrency::applyKeywords because uniqueIds must be set on declaration before resolution |
---|
342 | }); |
---|
343 | Stats::Time::TimeBlock("Hoist Control Declarations", [&]() { |
---|
344 | ControlStruct::hoistControlDecls( translationUnit ); // hoist initialization out of for statements; must happen before autogenerateRoutines |
---|
345 | }); |
---|
346 | Stats::Time::TimeBlock("Generate Autogen routines", [&]() { |
---|
347 | autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecay_old |
---|
348 | }); |
---|
349 | } |
---|
350 | PassVisitor<CompoundLiteral> compoundliteral; |
---|
351 | { |
---|
352 | Stats::Heap::newPass("validate-E"); |
---|
353 | Stats::Time::BlockGuard guard("validate-E"); |
---|
354 | Stats::Time::TimeBlock("Implement Mutex Func", [&]() { |
---|
355 | Concurrency::implementMutexFuncs( translationUnit ); |
---|
356 | }); |
---|
357 | Stats::Time::TimeBlock("Implement Thread Start", [&]() { |
---|
358 | Concurrency::implementThreadStarter( translationUnit ); |
---|
359 | }); |
---|
360 | Stats::Time::TimeBlock("Compound Literal", [&]() { |
---|
361 | mutateAll( translationUnit, compoundliteral ); |
---|
362 | }); |
---|
363 | if (!useNewAST) { |
---|
364 | Stats::Time::TimeBlock("Resolve With Expressions", [&]() { |
---|
365 | ResolvExpr::resolveWithExprs( translationUnit ); // must happen before FixObjectType because user-code is resolved and may contain with variables |
---|
366 | }); |
---|
367 | } |
---|
368 | } |
---|
369 | PassVisitor<LabelAddressFixer> labelAddrFixer; |
---|
370 | { |
---|
371 | Stats::Heap::newPass("validate-F"); |
---|
372 | Stats::Time::BlockGuard guard("validate-F"); |
---|
373 | if (!useNewAST) { |
---|
374 | Stats::Time::TimeCall("Fix Object Type", |
---|
375 | FixObjectType::fix, translationUnit); |
---|
376 | } |
---|
377 | Stats::Time::TimeCall("Initializer Length", |
---|
378 | InitializerLength::computeLength, translationUnit); |
---|
379 | if (!useNewAST) { |
---|
380 | Stats::Time::TimeCall("Array Length", |
---|
381 | ArrayLength::computeLength, translationUnit); |
---|
382 | } |
---|
383 | Stats::Time::TimeCall("Find Special Declarations", |
---|
384 | Validate::findSpecialDecls, translationUnit); |
---|
385 | Stats::Time::TimeCall("Fix Label Address", |
---|
386 | mutateAll<LabelAddressFixer>, translationUnit, labelAddrFixer); |
---|
387 | if (!useNewAST) { |
---|
388 | Stats::Time::TimeCall("Handle Attributes", |
---|
389 | Validate::handleAttributes, translationUnit); |
---|
390 | } |
---|
391 | } |
---|
392 | } |
---|
393 | |
---|
394 | void HoistTypeDecls::handleType( Type * type ) { |
---|
395 | // some type declarations are buried in expressions and not easy to hoist during parsing; hoist them here |
---|
396 | AggregateDecl * aggr = nullptr; |
---|
397 | if ( StructInstType * inst = dynamic_cast< StructInstType * >( type ) ) { |
---|
398 | aggr = inst->baseStruct; |
---|
399 | } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( type ) ) { |
---|
400 | aggr = inst->baseUnion; |
---|
401 | } else if ( EnumInstType * inst = dynamic_cast< EnumInstType * >( type ) ) { |
---|
402 | aggr = inst->baseEnum; |
---|
403 | } |
---|
404 | if ( aggr && aggr->body ) { |
---|
405 | declsToAddBefore.push_front( aggr ); |
---|
406 | } |
---|
407 | } |
---|
408 | |
---|
409 | void HoistTypeDecls::previsit( SizeofExpr * expr ) { |
---|
410 | handleType( expr->type ); |
---|
411 | } |
---|
412 | |
---|
413 | void HoistTypeDecls::previsit( AlignofExpr * expr ) { |
---|
414 | handleType( expr->type ); |
---|
415 | } |
---|
416 | |
---|
417 | void HoistTypeDecls::previsit( UntypedOffsetofExpr * expr ) { |
---|
418 | handleType( expr->type ); |
---|
419 | } |
---|
420 | |
---|
421 | void HoistTypeDecls::previsit( CompoundLiteralExpr * expr ) { |
---|
422 | handleType( expr->result ); |
---|
423 | } |
---|
424 | |
---|
425 | |
---|
426 | Type * FixQualifiedTypes::postmutate( QualifiedType * qualType ) { |
---|
427 | Type * parent = qualType->parent; |
---|
428 | Type * child = qualType->child; |
---|
429 | if ( dynamic_cast< GlobalScopeType * >( qualType->parent ) ) { |
---|
430 | // .T => lookup T at global scope |
---|
431 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) { |
---|
432 | auto td = indexer.globalLookupType( inst->name ); |
---|
433 | if ( ! td ) { |
---|
434 | SemanticError( qualType->location, toString("Use of undefined global type ", inst->name) ); |
---|
435 | } |
---|
436 | auto base = td->base; |
---|
437 | assert( base ); |
---|
438 | Type * ret = base->clone(); |
---|
439 | ret->get_qualifiers() = qualType->get_qualifiers(); |
---|
440 | return ret; |
---|
441 | } else { |
---|
442 | // .T => T is not a type name |
---|
443 | assertf( false, "unhandled global qualified child type: %s", toCString(child) ); |
---|
444 | } |
---|
445 | } else { |
---|
446 | // S.T => S must be an aggregate type, find the declaration for T in S. |
---|
447 | AggregateDecl * aggr = nullptr; |
---|
448 | if ( StructInstType * inst = dynamic_cast< StructInstType * >( parent ) ) { |
---|
449 | aggr = inst->baseStruct; |
---|
450 | } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * > ( parent ) ) { |
---|
451 | aggr = inst->baseUnion; |
---|
452 | } else { |
---|
453 | SemanticError( qualType->location, toString("Qualified type requires an aggregate on the left, but has: ", parent) ); |
---|
454 | } |
---|
455 | assert( aggr ); // TODO: need to handle forward declarations |
---|
456 | for ( Declaration * member : aggr->members ) { |
---|
457 | if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( child ) ) { |
---|
458 | // name on the right is a typedef |
---|
459 | if ( NamedTypeDecl * aggr = dynamic_cast< NamedTypeDecl * > ( member ) ) { |
---|
460 | if ( aggr->name == inst->name ) { |
---|
461 | assert( aggr->base ); |
---|
462 | Type * ret = aggr->base->clone(); |
---|
463 | ret->get_qualifiers() = qualType->get_qualifiers(); |
---|
464 | TypeSubstitution sub = parent->genericSubstitution(); |
---|
465 | sub.apply(ret); |
---|
466 | return ret; |
---|
467 | } |
---|
468 | } |
---|
469 | } else { |
---|
470 | // S.T - S is not an aggregate => error |
---|
471 | assertf( false, "unhandled qualified child type: %s", toCString(qualType) ); |
---|
472 | } |
---|
473 | } |
---|
474 | // failed to find a satisfying definition of type |
---|
475 | SemanticError( qualType->location, toString("Undefined type in qualified type: ", qualType) ); |
---|
476 | } |
---|
477 | |
---|
478 | // ... may want to link canonical SUE definition to each forward decl so that it becomes easier to lookup? |
---|
479 | } |
---|
480 | |
---|
481 | |
---|
482 | void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) { |
---|
483 | PassVisitor<HoistStruct> hoister; |
---|
484 | acceptAll( translationUnit, hoister ); |
---|
485 | } |
---|
486 | |
---|
487 | bool shouldHoist( Declaration * decl ) { |
---|
488 | return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl ) || dynamic_cast< StaticAssertDecl * >( decl ); |
---|
489 | } |
---|
490 | |
---|
491 | namespace { |
---|
492 | void qualifiedName( AggregateDecl * aggr, std::ostringstream & ss ) { |
---|
493 | if ( aggr->parent ) qualifiedName( aggr->parent, ss ); |
---|
494 | ss << "__" << aggr->name; |
---|
495 | } |
---|
496 | |
---|
497 | // mangle nested type names using entire parent chain |
---|
498 | std::string qualifiedName( AggregateDecl * aggr ) { |
---|
499 | std::ostringstream ss; |
---|
500 | qualifiedName( aggr, ss ); |
---|
501 | return ss.str(); |
---|
502 | } |
---|
503 | } |
---|
504 | |
---|
505 | template< typename AggDecl > |
---|
506 | void HoistStruct::handleAggregate( AggDecl * aggregateDecl ) { |
---|
507 | if ( parentAggr ) { |
---|
508 | aggregateDecl->parent = parentAggr; |
---|
509 | aggregateDecl->name = qualifiedName( aggregateDecl ); |
---|
510 | // Add elements in stack order corresponding to nesting structure. |
---|
511 | declsToAddBefore.push_front( aggregateDecl ); |
---|
512 | } else { |
---|
513 | GuardValue( parentAggr ); |
---|
514 | parentAggr = aggregateDecl; |
---|
515 | } // if |
---|
516 | // Always remove the hoisted aggregate from the inner structure. |
---|
517 | GuardAction( [aggregateDecl]() { filter( aggregateDecl->members, shouldHoist, false ); } ); |
---|
518 | } |
---|
519 | |
---|
520 | void HoistStruct::previsit( StaticAssertDecl * assertDecl ) { |
---|
521 | if ( parentAggr ) { |
---|
522 | declsToAddBefore.push_back( assertDecl ); |
---|
523 | } |
---|
524 | } |
---|
525 | |
---|
526 | void HoistStruct::previsit( StructDecl * aggregateDecl ) { |
---|
527 | handleAggregate( aggregateDecl ); |
---|
528 | } |
---|
529 | |
---|
530 | void HoistStruct::previsit( UnionDecl * aggregateDecl ) { |
---|
531 | handleAggregate( aggregateDecl ); |
---|
532 | } |
---|
533 | |
---|
534 | void HoistStruct::previsit( StructInstType * type ) { |
---|
535 | // need to reset type name after expanding to qualified name |
---|
536 | assert( type->baseStruct ); |
---|
537 | type->name = type->baseStruct->name; |
---|
538 | } |
---|
539 | |
---|
540 | void HoistStruct::previsit( UnionInstType * type ) { |
---|
541 | assert( type->baseUnion ); |
---|
542 | type->name = type->baseUnion->name; |
---|
543 | } |
---|
544 | |
---|
545 | void HoistStruct::previsit( EnumInstType * type ) { |
---|
546 | assert( type->baseEnum ); |
---|
547 | type->name = type->baseEnum->name; |
---|
548 | } |
---|
549 | |
---|
550 | |
---|
551 | bool isTypedef( Declaration * decl ) { |
---|
552 | return dynamic_cast< TypedefDecl * >( decl ); |
---|
553 | } |
---|
554 | |
---|
555 | void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) { |
---|
556 | PassVisitor<EliminateTypedef> eliminator; |
---|
557 | acceptAll( translationUnit, eliminator ); |
---|
558 | filter( translationUnit, isTypedef, true ); |
---|
559 | } |
---|
560 | |
---|
561 | template< typename AggDecl > |
---|
562 | void EliminateTypedef::handleAggregate( AggDecl * aggregateDecl ) { |
---|
563 | filter( aggregateDecl->members, isTypedef, true ); |
---|
564 | } |
---|
565 | |
---|
566 | void EliminateTypedef::previsit( StructDecl * aggregateDecl ) { |
---|
567 | handleAggregate( aggregateDecl ); |
---|
568 | } |
---|
569 | |
---|
570 | void EliminateTypedef::previsit( UnionDecl * aggregateDecl ) { |
---|
571 | handleAggregate( aggregateDecl ); |
---|
572 | } |
---|
573 | |
---|
574 | void EliminateTypedef::previsit( CompoundStmt * compoundStmt ) { |
---|
575 | // remove and delete decl stmts |
---|
576 | filter( compoundStmt->kids, [](Statement * stmt) { |
---|
577 | if ( DeclStmt * declStmt = dynamic_cast< DeclStmt * >( stmt ) ) { |
---|
578 | if ( dynamic_cast< TypedefDecl * >( declStmt->decl ) ) { |
---|
579 | return true; |
---|
580 | } // if |
---|
581 | } // if |
---|
582 | return false; |
---|
583 | }, true); |
---|
584 | } |
---|
585 | |
---|
586 | // expand assertions from trait instance, performing the appropriate type variable substitutions |
---|
587 | template< typename Iterator > |
---|
588 | void expandAssertions( TraitInstType * inst, Iterator out ) { |
---|
589 | assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) ); |
---|
590 | std::list< DeclarationWithType * > asserts; |
---|
591 | for ( Declaration * decl : inst->baseTrait->members ) { |
---|
592 | asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) ); |
---|
593 | } |
---|
594 | // substitute trait decl parameters for instance parameters |
---|
595 | applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out ); |
---|
596 | } |
---|
597 | |
---|
598 | ResolveEnumInitializers::ResolveEnumInitializers( const Indexer * other_indexer ) : WithIndexer( true ) { |
---|
599 | if ( other_indexer ) { |
---|
600 | local_indexer = other_indexer; |
---|
601 | } else { |
---|
602 | local_indexer = &indexer; |
---|
603 | } // if |
---|
604 | } |
---|
605 | |
---|
606 | void ResolveEnumInitializers::postvisit( EnumDecl * enumDecl ) { |
---|
607 | if ( enumDecl->body ) { |
---|
608 | for ( Declaration * member : enumDecl->members ) { |
---|
609 | ObjectDecl * field = strict_dynamic_cast<ObjectDecl *>( member ); |
---|
610 | if ( field->init ) { |
---|
611 | // need to resolve enumerator initializers early so that other passes that determine if an expression is constexpr have the appropriate information. |
---|
612 | SingleInit * init = strict_dynamic_cast<SingleInit *>( field->init ); |
---|
613 | if ( !enumDecl->base || dynamic_cast<BasicType *>(enumDecl->base)) |
---|
614 | ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer ); |
---|
615 | else { |
---|
616 | if (dynamic_cast<PointerType *>(enumDecl->base)) { |
---|
617 | auto typePtr = dynamic_cast<PointerType *>(enumDecl->base); |
---|
618 | ResolvExpr::findSingleExpression( init->value, |
---|
619 | new PointerType( Type::Qualifiers(), typePtr->base ), indexer ); |
---|
620 | } else { |
---|
621 | ResolvExpr::findSingleExpression( init->value, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), indexer ); |
---|
622 | } |
---|
623 | } |
---|
624 | } |
---|
625 | } |
---|
626 | |
---|
627 | } // if |
---|
628 | } |
---|
629 | |
---|
630 | /// Fix up assertions - flattens assertion lists, removing all trait instances |
---|
631 | void forallFixer( std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) { |
---|
632 | for ( TypeDecl * type : forall ) { |
---|
633 | std::list< DeclarationWithType * > asserts; |
---|
634 | asserts.splice( asserts.end(), type->assertions ); |
---|
635 | // expand trait instances into their members |
---|
636 | for ( DeclarationWithType * assertion : asserts ) { |
---|
637 | if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) { |
---|
638 | // expand trait instance into all of its members |
---|
639 | expandAssertions( traitInst, back_inserter( type->assertions ) ); |
---|
640 | delete traitInst; |
---|
641 | } else { |
---|
642 | // pass other assertions through |
---|
643 | type->assertions.push_back( assertion ); |
---|
644 | } // if |
---|
645 | } // for |
---|
646 | // apply FixFunction to every assertion to check for invalid void type |
---|
647 | for ( DeclarationWithType *& assertion : type->assertions ) { |
---|
648 | bool isVoid = fixFunction( assertion ); |
---|
649 | if ( isVoid ) { |
---|
650 | SemanticError( node, "invalid type void in assertion of function " ); |
---|
651 | } // if |
---|
652 | } // for |
---|
653 | // normalizeAssertions( type->assertions ); |
---|
654 | } // for |
---|
655 | } |
---|
656 | |
---|
657 | /// Replace all traits in assertion lists with their assertions. |
---|
658 | void expandTraits( std::list< TypeDecl * > & forall ) { |
---|
659 | for ( TypeDecl * type : forall ) { |
---|
660 | std::list< DeclarationWithType * > asserts; |
---|
661 | asserts.splice( asserts.end(), type->assertions ); |
---|
662 | // expand trait instances into their members |
---|
663 | for ( DeclarationWithType * assertion : asserts ) { |
---|
664 | if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) { |
---|
665 | // expand trait instance into all of its members |
---|
666 | expandAssertions( traitInst, back_inserter( type->assertions ) ); |
---|
667 | delete traitInst; |
---|
668 | } else { |
---|
669 | // pass other assertions through |
---|
670 | type->assertions.push_back( assertion ); |
---|
671 | } // if |
---|
672 | } // for |
---|
673 | } |
---|
674 | } |
---|
675 | |
---|
676 | /// Fix each function in the assertion list and check for invalid void type. |
---|
677 | void fixAssertions( |
---|
678 | std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) { |
---|
679 | for ( TypeDecl * type : forall ) { |
---|
680 | for ( DeclarationWithType *& assertion : type->assertions ) { |
---|
681 | bool isVoid = fixFunction( assertion ); |
---|
682 | if ( isVoid ) { |
---|
683 | SemanticError( node, "invalid type void in assertion of function " ); |
---|
684 | } // if |
---|
685 | } // for |
---|
686 | } |
---|
687 | } |
---|
688 | |
---|
689 | void ForallPointerDecay_old::previsit( ObjectDecl * object ) { |
---|
690 | // ensure that operator names only apply to functions or function pointers |
---|
691 | if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) { |
---|
692 | SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." ) ); |
---|
693 | } |
---|
694 | object->fixUniqueId(); |
---|
695 | } |
---|
696 | |
---|
697 | void ForallPointerDecay_old::previsit( FunctionDecl * func ) { |
---|
698 | func->fixUniqueId(); |
---|
699 | } |
---|
700 | |
---|
701 | void ForallPointerDecay_old::previsit( FunctionType * ftype ) { |
---|
702 | forallFixer( ftype->forall, ftype ); |
---|
703 | } |
---|
704 | |
---|
705 | void ForallPointerDecay_old::previsit( StructDecl * aggrDecl ) { |
---|
706 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
707 | } |
---|
708 | |
---|
709 | void ForallPointerDecay_old::previsit( UnionDecl * aggrDecl ) { |
---|
710 | forallFixer( aggrDecl->parameters, aggrDecl ); |
---|
711 | } |
---|
712 | |
---|
713 | void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) { |
---|
714 | PassVisitor<ReturnChecker> checker; |
---|
715 | acceptAll( translationUnit, checker ); |
---|
716 | } |
---|
717 | |
---|
718 | void ReturnChecker::previsit( FunctionDecl * functionDecl ) { |
---|
719 | GuardValue( returnVals ); |
---|
720 | returnVals = functionDecl->get_functionType()->get_returnVals(); |
---|
721 | } |
---|
722 | |
---|
723 | void ReturnChecker::previsit( ReturnStmt * returnStmt ) { |
---|
724 | // Previously this also checked for the existence of an expr paired with no return values on |
---|
725 | // the function return type. This is incorrect, since you can have an expression attached to |
---|
726 | // a return statement in a void-returning function in C. The expression is treated as if it |
---|
727 | // were cast to void. |
---|
728 | if ( ! returnStmt->get_expr() && returnVals.size() != 0 ) { |
---|
729 | SemanticError( returnStmt, "Non-void function returns no values: " ); |
---|
730 | } |
---|
731 | } |
---|
732 | |
---|
733 | |
---|
734 | void ReplaceTypedef::replaceTypedef( std::list< Declaration * > &translationUnit ) { |
---|
735 | PassVisitor<ReplaceTypedef> eliminator; |
---|
736 | mutateAll( translationUnit, eliminator ); |
---|
737 | if ( eliminator.pass.typedefNames.count( "size_t" ) ) { |
---|
738 | // grab and remember declaration of size_t |
---|
739 | Validate::SizeType = eliminator.pass.typedefNames["size_t"].first->base->clone(); |
---|
740 | } else { |
---|
741 | // xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong |
---|
742 | // eventually should have a warning for this case. |
---|
743 | Validate::SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ); |
---|
744 | } |
---|
745 | } |
---|
746 | |
---|
747 | void ReplaceTypedef::premutate( QualifiedType * ) { |
---|
748 | visit_children = false; |
---|
749 | } |
---|
750 | |
---|
751 | Type * ReplaceTypedef::postmutate( QualifiedType * qualType ) { |
---|
752 | // replacing typedefs only makes sense for the 'oldest ancestor' of the qualified type |
---|
753 | qualType->parent = qualType->parent->acceptMutator( * visitor ); |
---|
754 | return qualType; |
---|
755 | } |
---|
756 | |
---|
757 | static bool isNonParameterAttribute( Attribute * attr ) { |
---|
758 | static const std::vector<std::string> bad_names = { |
---|
759 | "aligned", "__aligned__", |
---|
760 | }; |
---|
761 | for ( auto name : bad_names ) { |
---|
762 | if ( name == attr->name ) { |
---|
763 | return true; |
---|
764 | } |
---|
765 | } |
---|
766 | return false; |
---|
767 | } |
---|
768 | |
---|
769 | Type * ReplaceTypedef::postmutate( TypeInstType * typeInst ) { |
---|
770 | // instances of typedef types will come here. If it is an instance |
---|
771 | // of a typdef type, link the instance to its actual type. |
---|
772 | TypedefMap::const_iterator def = typedefNames.find( typeInst->name ); |
---|
773 | if ( def != typedefNames.end() ) { |
---|
774 | Type * ret = def->second.first->base->clone(); |
---|
775 | ret->location = typeInst->location; |
---|
776 | ret->get_qualifiers() |= typeInst->get_qualifiers(); |
---|
777 | // GCC ignores certain attributes if they arrive by typedef, this mimics that. |
---|
778 | if ( inFunctionType ) { |
---|
779 | ret->attributes.remove_if( isNonParameterAttribute ); |
---|
780 | } |
---|
781 | ret->attributes.splice( ret->attributes.end(), typeInst->attributes ); |
---|
782 | // place instance parameters on the typedef'd type |
---|
783 | if ( ! typeInst->parameters.empty() ) { |
---|
784 | ReferenceToType * rtt = dynamic_cast<ReferenceToType *>(ret); |
---|
785 | if ( ! rtt ) { |
---|
786 | SemanticError( typeInst->location, "Cannot apply type parameters to base type of " + typeInst->name ); |
---|
787 | } |
---|
788 | rtt->parameters.clear(); |
---|
789 | cloneAll( typeInst->parameters, rtt->parameters ); |
---|
790 | mutateAll( rtt->parameters, * visitor ); // recursively fix typedefs on parameters |
---|
791 | } // if |
---|
792 | delete typeInst; |
---|
793 | return ret; |
---|
794 | } else { |
---|
795 | TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->name ); |
---|
796 | if ( base == typedeclNames.end() ) { |
---|
797 | SemanticError( typeInst->location, toString("Use of undefined type ", typeInst->name) ); |
---|
798 | } |
---|
799 | typeInst->set_baseType( base->second ); |
---|
800 | return typeInst; |
---|
801 | } // if |
---|
802 | assert( false ); |
---|
803 | } |
---|
804 | |
---|
805 | struct VarLenChecker : WithShortCircuiting { |
---|
806 | void previsit( FunctionType * ) { visit_children = false; } |
---|
807 | void previsit( ArrayType * at ) { |
---|
808 | isVarLen |= at->isVarLen; |
---|
809 | } |
---|
810 | bool isVarLen = false; |
---|
811 | }; |
---|
812 | |
---|
813 | bool isVariableLength( Type * t ) { |
---|
814 | PassVisitor<VarLenChecker> varLenChecker; |
---|
815 | maybeAccept( t, varLenChecker ); |
---|
816 | return varLenChecker.pass.isVarLen; |
---|
817 | } |
---|
818 | |
---|
819 | Declaration * ReplaceTypedef::postmutate( TypedefDecl * tyDecl ) { |
---|
820 | if ( typedefNames.count( tyDecl->name ) == 1 && typedefNames[ tyDecl->name ].second == scopeLevel ) { |
---|
821 | // typedef to the same name from the same scope |
---|
822 | // must be from the same type |
---|
823 | |
---|
824 | Type * t1 = tyDecl->base; |
---|
825 | Type * t2 = typedefNames[ tyDecl->name ].first->base; |
---|
826 | if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) { |
---|
827 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
828 | } |
---|
829 | // Cannot redefine VLA typedefs. Note: this is slightly incorrect, because our notion of VLAs |
---|
830 | // at this point in the translator is imprecise. In particular, this will disallow redefining typedefs |
---|
831 | // with arrays whose dimension is an enumerator or a cast of a constant/enumerator. The effort required |
---|
832 | // to fix this corner case likely outweighs the utility of allowing it. |
---|
833 | if ( isVariableLength( t1 ) || isVariableLength( t2 ) ) { |
---|
834 | SemanticError( tyDecl->location, "Cannot redefine typedef: " + tyDecl->name ); |
---|
835 | } |
---|
836 | } else { |
---|
837 | typedefNames[ tyDecl->name ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel ); |
---|
838 | } // if |
---|
839 | |
---|
840 | // When a typedef is a forward declaration: |
---|
841 | // typedef struct screen SCREEN; |
---|
842 | // the declaration portion must be retained: |
---|
843 | // struct screen; |
---|
844 | // because the expansion of the typedef is: |
---|
845 | // void rtn( SCREEN * p ) => void rtn( struct screen * p ) |
---|
846 | // hence the type-name "screen" must be defined. |
---|
847 | // Note, qualifiers on the typedef are superfluous for the forward declaration. |
---|
848 | |
---|
849 | Type * designatorType = tyDecl->base->stripDeclarator(); |
---|
850 | if ( StructInstType * aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) { |
---|
851 | declsToAddBefore.push_back( new StructDecl( aggDecl->name, AggregateDecl::Struct, noAttributes, tyDecl->linkage ) ); |
---|
852 | } else if ( UnionInstType * aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) { |
---|
853 | declsToAddBefore.push_back( new UnionDecl( aggDecl->name, noAttributes, tyDecl->linkage ) ); |
---|
854 | } else if ( EnumInstType * enumInst = dynamic_cast< EnumInstType * >( designatorType ) ) { |
---|
855 | if ( enumInst->baseEnum ) { |
---|
856 | const EnumDecl * enumDecl = enumInst->baseEnum; |
---|
857 | declsToAddBefore.push_back( new EnumDecl( enumDecl->name, noAttributes, enumDecl->isTyped, tyDecl->linkage, enumDecl->base ) ); |
---|
858 | } else { |
---|
859 | declsToAddBefore.push_back( new EnumDecl( enumInst->name, noAttributes, tyDecl->linkage ) ); |
---|
860 | } |
---|
861 | } // if |
---|
862 | return tyDecl->clone(); |
---|
863 | } |
---|
864 | |
---|
865 | void ReplaceTypedef::premutate( TypeDecl * typeDecl ) { |
---|
866 | typedefNames.erase( typeDecl->name ); |
---|
867 | typedeclNames.insert( typeDecl->name, typeDecl ); |
---|
868 | } |
---|
869 | |
---|
870 | void ReplaceTypedef::premutate( FunctionDecl * ) { |
---|
871 | GuardScope( typedefNames ); |
---|
872 | GuardScope( typedeclNames ); |
---|
873 | } |
---|
874 | |
---|
875 | void ReplaceTypedef::premutate( ObjectDecl * ) { |
---|
876 | GuardScope( typedefNames ); |
---|
877 | GuardScope( typedeclNames ); |
---|
878 | } |
---|
879 | |
---|
880 | DeclarationWithType * ReplaceTypedef::postmutate( ObjectDecl * objDecl ) { |
---|
881 | if ( FunctionType * funtype = dynamic_cast<FunctionType *>( objDecl->type ) ) { // function type? |
---|
882 | // replace the current object declaration with a function declaration |
---|
883 | FunctionDecl * newDecl = new FunctionDecl( objDecl->name, objDecl->get_storageClasses(), objDecl->linkage, funtype, 0, objDecl->attributes, objDecl->get_funcSpec() ); |
---|
884 | objDecl->attributes.clear(); |
---|
885 | objDecl->set_type( nullptr ); |
---|
886 | delete objDecl; |
---|
887 | return newDecl; |
---|
888 | } // if |
---|
889 | return objDecl; |
---|
890 | } |
---|
891 | |
---|
892 | void ReplaceTypedef::premutate( CastExpr * ) { |
---|
893 | GuardScope( typedefNames ); |
---|
894 | GuardScope( typedeclNames ); |
---|
895 | } |
---|
896 | |
---|
897 | void ReplaceTypedef::premutate( CompoundStmt * ) { |
---|
898 | GuardScope( typedefNames ); |
---|
899 | GuardScope( typedeclNames ); |
---|
900 | scopeLevel += 1; |
---|
901 | GuardAction( [this](){ scopeLevel -= 1; } ); |
---|
902 | } |
---|
903 | |
---|
904 | template<typename AggDecl> |
---|
905 | void ReplaceTypedef::addImplicitTypedef( AggDecl * aggDecl ) { |
---|
906 | if ( typedefNames.count( aggDecl->get_name() ) == 0 ) { |
---|
907 | Type * type = nullptr; |
---|
908 | if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) { |
---|
909 | type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() ); |
---|
910 | } else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) { |
---|
911 | type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() ); |
---|
912 | } else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl ) ) { |
---|
913 | type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() ); |
---|
914 | } // if |
---|
915 | TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type, aggDecl->get_linkage() ) ); |
---|
916 | typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel ); |
---|
917 | // add the implicit typedef to the AST |
---|
918 | declsToAddBefore.push_back( new TypedefDecl( aggDecl->get_name(), aggDecl->location, Type::StorageClasses(), type->clone(), aggDecl->get_linkage() ) ); |
---|
919 | } // if |
---|
920 | } |
---|
921 | |
---|
922 | template< typename AggDecl > |
---|
923 | void ReplaceTypedef::handleAggregate( AggDecl * aggr ) { |
---|
924 | SemanticErrorException errors; |
---|
925 | |
---|
926 | ValueGuard< std::list<Declaration * > > oldBeforeDecls( declsToAddBefore ); |
---|
927 | ValueGuard< std::list<Declaration * > > oldAfterDecls ( declsToAddAfter ); |
---|
928 | declsToAddBefore.clear(); |
---|
929 | declsToAddAfter.clear(); |
---|
930 | |
---|
931 | GuardScope( typedefNames ); |
---|
932 | GuardScope( typedeclNames ); |
---|
933 | mutateAll( aggr->parameters, * visitor ); |
---|
934 | mutateAll( aggr->attributes, * visitor ); |
---|
935 | |
---|
936 | // unroll mutateAll for aggr->members so that implicit typedefs for nested types are added to the aggregate body. |
---|
937 | for ( std::list< Declaration * >::iterator i = aggr->members.begin(); i != aggr->members.end(); ++i ) { |
---|
938 | if ( !declsToAddAfter.empty() ) { aggr->members.splice( i, declsToAddAfter ); } |
---|
939 | |
---|
940 | try { |
---|
941 | * i = maybeMutate( * i, * visitor ); |
---|
942 | } catch ( SemanticErrorException &e ) { |
---|
943 | errors.append( e ); |
---|
944 | } |
---|
945 | |
---|
946 | if ( !declsToAddBefore.empty() ) { aggr->members.splice( i, declsToAddBefore ); } |
---|
947 | } |
---|
948 | |
---|
949 | if ( !declsToAddAfter.empty() ) { aggr->members.splice( aggr->members.end(), declsToAddAfter ); } |
---|
950 | if ( !errors.isEmpty() ) { throw errors; } |
---|
951 | } |
---|
952 | |
---|
953 | void ReplaceTypedef::premutate( StructDecl * structDecl ) { |
---|
954 | visit_children = false; |
---|
955 | addImplicitTypedef( structDecl ); |
---|
956 | handleAggregate( structDecl ); |
---|
957 | } |
---|
958 | |
---|
959 | void ReplaceTypedef::premutate( UnionDecl * unionDecl ) { |
---|
960 | visit_children = false; |
---|
961 | addImplicitTypedef( unionDecl ); |
---|
962 | handleAggregate( unionDecl ); |
---|
963 | } |
---|
964 | |
---|
965 | void ReplaceTypedef::premutate( EnumDecl * enumDecl ) { |
---|
966 | addImplicitTypedef( enumDecl ); |
---|
967 | } |
---|
968 | |
---|
969 | void ReplaceTypedef::premutate( FunctionType * ) { |
---|
970 | GuardValue( inFunctionType ); |
---|
971 | inFunctionType = true; |
---|
972 | } |
---|
973 | |
---|
974 | void ReplaceTypedef::premutate( TraitDecl * ) { |
---|
975 | GuardScope( typedefNames ); |
---|
976 | GuardScope( typedeclNames); |
---|
977 | } |
---|
978 | |
---|
979 | void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) { |
---|
980 | PassVisitor<VerifyCtorDtorAssign> verifier; |
---|
981 | acceptAll( translationUnit, verifier ); |
---|
982 | } |
---|
983 | |
---|
984 | void VerifyCtorDtorAssign::previsit( FunctionDecl * funcDecl ) { |
---|
985 | FunctionType * funcType = funcDecl->get_functionType(); |
---|
986 | std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals(); |
---|
987 | std::list< DeclarationWithType * > ¶ms = funcType->get_parameters(); |
---|
988 | |
---|
989 | if ( CodeGen::isCtorDtorAssign( funcDecl->get_name() ) ) { // TODO: also check /=, etc. |
---|
990 | if ( params.size() == 0 ) { |
---|
991 | SemanticError( funcDecl->location, "Constructors, destructors, and assignment functions require at least one parameter." ); |
---|
992 | } |
---|
993 | ReferenceType * refType = dynamic_cast< ReferenceType * >( params.front()->get_type() ); |
---|
994 | if ( ! refType ) { |
---|
995 | SemanticError( funcDecl->location, "First parameter of a constructor, destructor, or assignment function must be a reference." ); |
---|
996 | } |
---|
997 | if ( CodeGen::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) { |
---|
998 | if(!returnVals.front()->get_type()->isVoid()) { |
---|
999 | SemanticError( funcDecl->location, "Constructors and destructors cannot have explicit return values." ); |
---|
1000 | } |
---|
1001 | } |
---|
1002 | } |
---|
1003 | } |
---|
1004 | |
---|
1005 | // Test for special name on a generic parameter. Special treatment for the |
---|
1006 | // special name is a bootstrapping hack. In most cases, the worlds of T's |
---|
1007 | // and of N's don't overlap (normal treamtemt). The foundations in |
---|
1008 | // array.hfa use tagging for both types and dimensions. Tagging treats |
---|
1009 | // its subject parameter even more opaquely than T&, which assumes it is |
---|
1010 | // possible to have a pointer/reference to such an object. Tagging only |
---|
1011 | // seeks to identify the type-system resident at compile time. Both N's |
---|
1012 | // and T's can make tags. The tag definition uses the special name, which |
---|
1013 | // is treated as "an N or a T." This feature is not inteded to be used |
---|
1014 | // outside of the definition and immediate uses of a tag. |
---|
1015 | static inline bool isReservedTysysIdOnlyName( const std::string & name ) { |
---|
1016 | // name's prefix was __CFA_tysys_id_only, before it got wrapped in __..._generic |
---|
1017 | int foundAt = name.find("__CFA_tysys_id_only"); |
---|
1018 | if (foundAt == 0) return true; |
---|
1019 | if (foundAt == 2 && name[0] == '_' && name[1] == '_') return true; |
---|
1020 | return false; |
---|
1021 | } |
---|
1022 | |
---|
1023 | template< typename Aggr > |
---|
1024 | void validateGeneric( Aggr * inst ) { |
---|
1025 | std::list< TypeDecl * > * params = inst->get_baseParameters(); |
---|
1026 | if ( params ) { |
---|
1027 | std::list< Expression * > & args = inst->get_parameters(); |
---|
1028 | |
---|
1029 | // insert defaults arguments when a type argument is missing (currently only supports missing arguments at the end of the list). |
---|
1030 | // A substitution is used to ensure that defaults are replaced correctly, e.g., |
---|
1031 | // forall(otype T, otype alloc = heap_allocator(T)) struct vector; |
---|
1032 | // vector(int) v; |
---|
1033 | // after insertion of default values becomes |
---|
1034 | // vector(int, heap_allocator(T)) |
---|
1035 | // and the substitution is built with T=int so that after substitution, the result is |
---|
1036 | // vector(int, heap_allocator(int)) |
---|
1037 | TypeSubstitution sub; |
---|
1038 | auto paramIter = params->begin(); |
---|
1039 | auto argIter = args.begin(); |
---|
1040 | for ( ; paramIter != params->end(); ++paramIter, ++argIter ) { |
---|
1041 | if ( argIter != args.end() ) { |
---|
1042 | TypeExpr * expr = dynamic_cast< TypeExpr * >( * argIter ); |
---|
1043 | if ( expr ) { |
---|
1044 | sub.add( (* paramIter)->get_name(), expr->get_type()->clone() ); |
---|
1045 | } |
---|
1046 | } else { |
---|
1047 | Type * defaultType = (* paramIter)->get_init(); |
---|
1048 | if ( defaultType ) { |
---|
1049 | args.push_back( new TypeExpr( defaultType->clone() ) ); |
---|
1050 | sub.add( (* paramIter)->get_name(), defaultType->clone() ); |
---|
1051 | argIter = std::prev(args.end()); |
---|
1052 | } else { |
---|
1053 | SemanticError( inst, "Too few type arguments in generic type " ); |
---|
1054 | } |
---|
1055 | } |
---|
1056 | assert( argIter != args.end() ); |
---|
1057 | bool typeParamDeclared = (*paramIter)->kind != TypeDecl::Kind::Dimension; |
---|
1058 | bool typeArgGiven; |
---|
1059 | if ( isReservedTysysIdOnlyName( (*paramIter)->name ) ) { |
---|
1060 | // coerce a match when declaration is reserved name, which means "either" |
---|
1061 | typeArgGiven = typeParamDeclared; |
---|
1062 | } else { |
---|
1063 | typeArgGiven = dynamic_cast< TypeExpr * >( * argIter ); |
---|
1064 | } |
---|
1065 | if ( ! typeParamDeclared && typeArgGiven ) SemanticError( inst, "Type argument given for value parameter: " ); |
---|
1066 | if ( typeParamDeclared && ! typeArgGiven ) SemanticError( inst, "Expression argument given for type parameter: " ); |
---|
1067 | } |
---|
1068 | |
---|
1069 | sub.apply( inst ); |
---|
1070 | if ( args.size() > params->size() ) SemanticError( inst, "Too many type arguments in generic type " ); |
---|
1071 | } |
---|
1072 | } |
---|
1073 | |
---|
1074 | void ValidateGenericParameters::previsit( StructInstType * inst ) { |
---|
1075 | validateGeneric( inst ); |
---|
1076 | } |
---|
1077 | |
---|
1078 | void ValidateGenericParameters::previsit( UnionInstType * inst ) { |
---|
1079 | validateGeneric( inst ); |
---|
1080 | } |
---|
1081 | |
---|
1082 | void TranslateDimensionGenericParameters::translateDimensions( std::list< Declaration * > &translationUnit ) { |
---|
1083 | PassVisitor<TranslateDimensionGenericParameters> translator; |
---|
1084 | mutateAll( translationUnit, translator ); |
---|
1085 | } |
---|
1086 | |
---|
1087 | TranslateDimensionGenericParameters::TranslateDimensionGenericParameters() : WithIndexer( false ) {} |
---|
1088 | |
---|
1089 | // Declaration of type variable: forall( [N] ) -> forall( N & | sized( N ) ) |
---|
1090 | TypeDecl * TranslateDimensionGenericParameters::postmutate( TypeDecl * td ) { |
---|
1091 | if ( td->kind == TypeDecl::Dimension ) { |
---|
1092 | td->kind = TypeDecl::Dtype; |
---|
1093 | if ( ! isReservedTysysIdOnlyName( td->name ) ) { |
---|
1094 | td->sized = true; |
---|
1095 | } |
---|
1096 | } |
---|
1097 | return td; |
---|
1098 | } |
---|
1099 | |
---|
1100 | // Situational awareness: |
---|
1101 | // array( float, [[currentExpr]] ) has visitingChildOfSUIT == true |
---|
1102 | // array( float, [[currentExpr]] - 1 ) has visitingChildOfSUIT == false |
---|
1103 | // size_t x = [[currentExpr]] has visitingChildOfSUIT == false |
---|
1104 | void TranslateDimensionGenericParameters::changeState_ChildOfSUIT( bool newVal ) { |
---|
1105 | GuardValue( nextVisitedNodeIsChildOfSUIT ); |
---|
1106 | GuardValue( visitingChildOfSUIT ); |
---|
1107 | visitingChildOfSUIT = nextVisitedNodeIsChildOfSUIT; |
---|
1108 | nextVisitedNodeIsChildOfSUIT = newVal; |
---|
1109 | } |
---|
1110 | void TranslateDimensionGenericParameters::premutate( StructInstType * sit ) { |
---|
1111 | (void) sit; |
---|
1112 | changeState_ChildOfSUIT(true); |
---|
1113 | } |
---|
1114 | void TranslateDimensionGenericParameters::premutate( UnionInstType * uit ) { |
---|
1115 | (void) uit; |
---|
1116 | changeState_ChildOfSUIT(true); |
---|
1117 | } |
---|
1118 | void TranslateDimensionGenericParameters::premutate( BaseSyntaxNode * node ) { |
---|
1119 | (void) node; |
---|
1120 | changeState_ChildOfSUIT(false); |
---|
1121 | } |
---|
1122 | |
---|
1123 | // Passing values as dimension arguments: array( float, 7 ) -> array( float, char[ 7 ] ) |
---|
1124 | // Consuming dimension parameters: size_t x = N - 1 ; -> size_t x = sizeof(N) - 1 ; |
---|
1125 | // Intertwined reality: array( float, N ) -> array( float, N ) |
---|
1126 | // array( float, N - 1 ) -> array( float, char[ sizeof(N) - 1 ] ) |
---|
1127 | // Intertwined case 1 is not just an optimization. |
---|
1128 | // Avoiding char[sizeof(-)] is necessary to enable the call of f to bind the value of N, in: |
---|
1129 | // forall([N]) void f( array(float, N) & ); |
---|
1130 | // array(float, 7) a; |
---|
1131 | // f(a); |
---|
1132 | |
---|
1133 | Expression * TranslateDimensionGenericParameters::postmutate( DimensionExpr * de ) { |
---|
1134 | // Expression de is an occurrence of N in LHS of above examples. |
---|
1135 | // Look up the name that de references. |
---|
1136 | // If we are in a struct body, then this reference can be to an entry of the stuct's forall list. |
---|
1137 | // Whether or not we are in a struct body, this reference can be to an entry of a containing function's forall list. |
---|
1138 | // If we are in a struct body, then the stuct's forall declarations are innermost (functions don't occur in structs). |
---|
1139 | // Thus, a potential struct's declaration is highest priority. |
---|
1140 | // A struct's forall declarations are already renamed with _generic_ suffix. Try that name variant first. |
---|
1141 | |
---|
1142 | std::string useName = "__" + de->name + "_generic_"; |
---|
1143 | TypeDecl * namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) ); |
---|
1144 | |
---|
1145 | if ( ! namedParamDecl ) { |
---|
1146 | useName = de->name; |
---|
1147 | namedParamDecl = const_cast<TypeDecl *>( strict_dynamic_cast<const TypeDecl *, nullptr >( indexer.lookupType( useName ) ) ); |
---|
1148 | } |
---|
1149 | |
---|
1150 | // Expect to find it always. A misspelled name would have been parsed as an identifier. |
---|
1151 | assert( namedParamDecl && "Type-system-managed value name not found in symbol table" ); |
---|
1152 | |
---|
1153 | delete de; |
---|
1154 | |
---|
1155 | TypeInstType * refToDecl = new TypeInstType( 0, useName, namedParamDecl ); |
---|
1156 | |
---|
1157 | if ( visitingChildOfSUIT ) { |
---|
1158 | // As in postmutate( Expression * ), topmost expression needs a TypeExpr wrapper |
---|
1159 | // But avoid ArrayType-Sizeof |
---|
1160 | return new TypeExpr( refToDecl ); |
---|
1161 | } else { |
---|
1162 | // the N occurrence is being used directly as a runtime value, |
---|
1163 | // if we are in a type instantiation, then the N is within a bigger value computation |
---|
1164 | return new SizeofExpr( refToDecl ); |
---|
1165 | } |
---|
1166 | } |
---|
1167 | |
---|
1168 | Expression * TranslateDimensionGenericParameters::postmutate( Expression * e ) { |
---|
1169 | if ( visitingChildOfSUIT ) { |
---|
1170 | // e is an expression used as an argument to instantiate a type |
---|
1171 | if (! dynamic_cast< TypeExpr * >( e ) ) { |
---|
1172 | // e is a value expression |
---|
1173 | // but not a DimensionExpr, which has a distinct postmutate |
---|
1174 | Type * typeExprContent = new ArrayType( 0, new BasicType( 0, BasicType::Char ), e, true, false ); |
---|
1175 | TypeExpr * result = new TypeExpr( typeExprContent ); |
---|
1176 | return result; |
---|
1177 | } |
---|
1178 | } |
---|
1179 | return e; |
---|
1180 | } |
---|
1181 | |
---|
1182 | void CompoundLiteral::premutate( ObjectDecl * objectDecl ) { |
---|
1183 | storageClasses = objectDecl->get_storageClasses(); |
---|
1184 | } |
---|
1185 | |
---|
1186 | Expression * CompoundLiteral::postmutate( CompoundLiteralExpr * compLitExpr ) { |
---|
1187 | // transform [storage_class] ... (struct S){ 3, ... }; |
---|
1188 | // into [storage_class] struct S temp = { 3, ... }; |
---|
1189 | static UniqueName indexName( "_compLit" ); |
---|
1190 | |
---|
1191 | ObjectDecl * tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, nullptr, compLitExpr->get_result(), compLitExpr->get_initializer() ); |
---|
1192 | compLitExpr->set_result( nullptr ); |
---|
1193 | compLitExpr->set_initializer( nullptr ); |
---|
1194 | delete compLitExpr; |
---|
1195 | declsToAddBefore.push_back( tempvar ); // add modified temporary to current block |
---|
1196 | return new VariableExpr( tempvar ); |
---|
1197 | } |
---|
1198 | |
---|
1199 | void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) { |
---|
1200 | PassVisitor<ReturnTypeFixer> fixer; |
---|
1201 | acceptAll( translationUnit, fixer ); |
---|
1202 | } |
---|
1203 | |
---|
1204 | void ReturnTypeFixer::postvisit( FunctionDecl * functionDecl ) { |
---|
1205 | FunctionType * ftype = functionDecl->get_functionType(); |
---|
1206 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
1207 | assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %zu", functionDecl->get_name().c_str(), retVals.size() ); |
---|
1208 | if ( retVals.size() == 1 ) { |
---|
1209 | // 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). |
---|
1210 | // ensure other return values have a name. |
---|
1211 | DeclarationWithType * ret = retVals.front(); |
---|
1212 | if ( ret->get_name() == "" ) { |
---|
1213 | ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) ); |
---|
1214 | } |
---|
1215 | ret->get_attributes().push_back( new Attribute( "unused" ) ); |
---|
1216 | } |
---|
1217 | } |
---|
1218 | |
---|
1219 | void ReturnTypeFixer::postvisit( FunctionType * ftype ) { |
---|
1220 | // xxx - need to handle named return values - this information needs to be saved somehow |
---|
1221 | // so that resolution has access to the names. |
---|
1222 | // Note that this pass needs to happen early so that other passes which look for tuple types |
---|
1223 | // find them in all of the right places, including function return types. |
---|
1224 | std::list< DeclarationWithType * > & retVals = ftype->get_returnVals(); |
---|
1225 | if ( retVals.size() > 1 ) { |
---|
1226 | // generate a single return parameter which is the tuple of all of the return values |
---|
1227 | TupleType * tupleType = strict_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) ); |
---|
1228 | // ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false. |
---|
1229 | ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer *>(), noDesignators, false ) ); |
---|
1230 | deleteAll( retVals ); |
---|
1231 | retVals.clear(); |
---|
1232 | retVals.push_back( newRet ); |
---|
1233 | } |
---|
1234 | } |
---|
1235 | |
---|
1236 | void FixObjectType::fix( std::list< Declaration * > & translationUnit ) { |
---|
1237 | PassVisitor<FixObjectType> fixer; |
---|
1238 | acceptAll( translationUnit, fixer ); |
---|
1239 | } |
---|
1240 | |
---|
1241 | void FixObjectType::previsit( ObjectDecl * objDecl ) { |
---|
1242 | Type * new_type = ResolvExpr::resolveTypeof( objDecl->get_type(), indexer ); |
---|
1243 | objDecl->set_type( new_type ); |
---|
1244 | } |
---|
1245 | |
---|
1246 | void FixObjectType::previsit( FunctionDecl * funcDecl ) { |
---|
1247 | Type * new_type = ResolvExpr::resolveTypeof( funcDecl->type, indexer ); |
---|
1248 | funcDecl->set_type( new_type ); |
---|
1249 | } |
---|
1250 | |
---|
1251 | void FixObjectType::previsit( TypeDecl * typeDecl ) { |
---|
1252 | if ( typeDecl->get_base() ) { |
---|
1253 | Type * new_type = ResolvExpr::resolveTypeof( typeDecl->get_base(), indexer ); |
---|
1254 | typeDecl->set_base( new_type ); |
---|
1255 | } // if |
---|
1256 | } |
---|
1257 | |
---|
1258 | void InitializerLength::computeLength( std::list< Declaration * > & translationUnit ) { |
---|
1259 | PassVisitor<InitializerLength> len; |
---|
1260 | acceptAll( translationUnit, len ); |
---|
1261 | } |
---|
1262 | |
---|
1263 | void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) { |
---|
1264 | PassVisitor<ArrayLength> len; |
---|
1265 | acceptAll( translationUnit, len ); |
---|
1266 | } |
---|
1267 | |
---|
1268 | void InitializerLength::previsit( ObjectDecl * objDecl ) { |
---|
1269 | if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->type ) ) { |
---|
1270 | if ( at->dimension ) return; |
---|
1271 | if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->init ) ) { |
---|
1272 | at->dimension = new ConstantExpr( Constant::from_ulong( init->initializers.size() ) ); |
---|
1273 | } |
---|
1274 | } |
---|
1275 | } |
---|
1276 | |
---|
1277 | void ArrayLength::previsit( ArrayType * type ) { |
---|
1278 | if ( type->dimension ) { |
---|
1279 | // need to resolve array dimensions early so that constructor code can correctly determine |
---|
1280 | // if a type is a VLA (and hence whether its elements need to be constructed) |
---|
1281 | ResolvExpr::findSingleExpression( type->dimension, Validate::SizeType->clone(), indexer ); |
---|
1282 | |
---|
1283 | // must re-evaluate whether a type is a VLA, now that more information is available |
---|
1284 | // (e.g. the dimension may have been an enumerator, which was unknown prior to this step) |
---|
1285 | type->isVarLen = ! InitTweak::isConstExpr( type->dimension ); |
---|
1286 | } |
---|
1287 | } |
---|
1288 | |
---|
1289 | struct LabelFinder { |
---|
1290 | std::set< Label > & labels; |
---|
1291 | LabelFinder( std::set< Label > & labels ) : labels( labels ) {} |
---|
1292 | void previsit( Statement * stmt ) { |
---|
1293 | for ( Label & l : stmt->labels ) { |
---|
1294 | labels.insert( l ); |
---|
1295 | } |
---|
1296 | } |
---|
1297 | }; |
---|
1298 | |
---|
1299 | void LabelAddressFixer::premutate( FunctionDecl * funcDecl ) { |
---|
1300 | GuardValue( labels ); |
---|
1301 | PassVisitor<LabelFinder> finder( labels ); |
---|
1302 | funcDecl->accept( finder ); |
---|
1303 | } |
---|
1304 | |
---|
1305 | Expression * LabelAddressFixer::postmutate( AddressExpr * addrExpr ) { |
---|
1306 | // convert &&label into label address |
---|
1307 | if ( AddressExpr * inner = dynamic_cast< AddressExpr * >( addrExpr->arg ) ) { |
---|
1308 | if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( inner->arg ) ) { |
---|
1309 | if ( labels.count( nameExpr->name ) ) { |
---|
1310 | Label name = nameExpr->name; |
---|
1311 | delete addrExpr; |
---|
1312 | return new LabelAddressExpr( name ); |
---|
1313 | } |
---|
1314 | } |
---|
1315 | } |
---|
1316 | return addrExpr; |
---|
1317 | } |
---|
1318 | |
---|
1319 | } // namespace SymTab |
---|
1320 | |
---|
1321 | // Local Variables: // |
---|
1322 | // tab-width: 4 // |
---|
1323 | // mode: c++ // |
---|
1324 | // compile-command: "make install" // |
---|
1325 | // End: // |
---|