source: src/AST/Pass.proto.hpp @ 8631c84

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 8631c84 was eb211bf, checked in by Andrew Beach <ajbeach@…>, 2 years ago

Did some clean-up with the ast::Pass class. Moved some things out of the main header and cut out some duplication.

  • Property mode set to 100644
File size: 16.9 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2019 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// Pass.impl.hpp --
8//
9// Author           : Thierry Delisle
10// Created On       : Thu May 09 15::37::05 2019
11// Last Modified By :
12// Last Modified On :
13// Update Count     :
14//
15
16#pragma once
17// IWYU pragma: private, include "Pass.hpp"
18
19#include "Common/Stats/Heap.h"
20
21namespace ast {
22template<typename core_t>
23class Pass;
24
25class TranslationUnit;
26
27struct PureVisitor;
28
29namespace __pass {
30        typedef std::function<void( void * )> cleanup_func_t;
31        typedef std::function<void( cleanup_func_t, void * )> at_cleanup_t;
32
33
34        // boolean reference that may be null
35        // either refers to a boolean value or is null and returns true
36        class bool_ref {
37        public:
38                bool_ref() = default;
39                ~bool_ref() = default;
40
41                operator bool() { return m_ref ? *m_ref : true; }
42                bool operator=( bool val ) { assert(m_ref); return *m_ref = val; }
43
44        private:
45
46                friend class visit_children_guard;
47
48                bool * set( bool * val ) {
49                        bool * prev = m_ref;
50                        m_ref = val;
51                        return prev;
52                }
53
54                bool * m_ref = nullptr;
55        };
56
57        // Implementation of the guard value
58        // Created inside the visit scope
59        class guard_value {
60        public:
61                /// Push onto the cleanup
62                guard_value( at_cleanup_t * at_cleanup ) {
63                        if( at_cleanup ) {
64                                *at_cleanup = [this]( cleanup_func_t && func, void* val ) {
65                                        push( std::move( func ), val );
66                                };
67                        }
68                }
69
70                ~guard_value() {
71                        while( !cleanups.empty() ) {
72                                auto& cleanup = cleanups.top();
73                                cleanup.func( cleanup.val );
74                                cleanups.pop();
75                        }
76                }
77
78                void push( cleanup_func_t && func, void* val ) {
79                        cleanups.emplace( std::move(func), val );
80                }
81
82        private:
83                struct cleanup_t {
84                        cleanup_func_t func;
85                        void * val;
86
87                        cleanup_t( cleanup_func_t&& func, void * val ) : func(func), val(val) {}
88                };
89
90                std::stack< cleanup_t, std::vector<cleanup_t> > cleanups;
91        };
92
93        // Guard structure implementation for whether or not children should be visited
94        class visit_children_guard {
95        public:
96
97                visit_children_guard( bool_ref * ref )
98                        : m_val ( true )
99                        , m_prev( ref ? ref->set( &m_val ) : nullptr )
100                        , m_ref ( ref )
101                {}
102
103                ~visit_children_guard() {
104                        if( m_ref ) {
105                                m_ref->set( m_prev );
106                        }
107                }
108
109                operator bool() { return m_val; }
110
111        private:
112                bool       m_val;
113                bool     * m_prev;
114                bool_ref * m_ref;
115        };
116
117        /// "Short hand" to check if this is a valid previsit function
118        /// Mostly used to make the static_assert look (and print) prettier
119        template<typename core_t, typename node_t>
120        struct is_valid_previsit {
121                using ret_t = decltype( std::declval<core_t*>()->previsit( std::declval<const node_t *>() ) );
122
123                static constexpr bool value = std::is_void< ret_t >::value ||
124                        std::is_base_of<const node_t, typename std::remove_pointer<ret_t>::type >::value;
125        };
126
127        /// The result is a single node.
128        template< typename node_t >
129        struct result1 {
130                bool differs;
131                const node_t * value;
132
133                template< typename object_t, typename super_t, typename field_t >
134                void apply( object_t *, field_t super_t::* field );
135        };
136
137        /// The result is a container of statements.
138        template< template<class...> class container_t >
139        struct resultNstmt {
140                /// The delta/change on a single node.
141                struct delta {
142                        ptr<Stmt> new_val;
143                        ssize_t old_idx;
144                        bool is_old;
145
146                        delta(const Stmt * s, ssize_t i, bool old) :
147                                new_val(s), old_idx(i), is_old(old) {}
148                };
149
150                bool differs;
151                container_t< delta > values;
152
153                template< typename object_t, typename super_t, typename field_t >
154                void apply( object_t *, field_t super_t::* field );
155
156                template< template<class...> class incontainer_t >
157                void take_all( incontainer_t<ptr<Stmt>> * stmts );
158
159                template< template<class...> class incontainer_t >
160                void take_all( incontainer_t<ptr<Decl>> * decls );
161        };
162
163        /// The result is a container of nodes.
164        template< template<class...> class container_t, typename node_t >
165        struct resultN {
166                bool differs;
167                container_t<ptr<node_t>> values;
168
169                template< typename object_t, typename super_t, typename field_t >
170                void apply( object_t *, field_t super_t::* field );
171        };
172
173        /// Used by previsit implementation
174        /// We need to reassign the result to 'node', unless the function
175        /// returns void, then we just leave 'node' unchanged
176        template<bool is_void>
177        struct __assign;
178
179        template<>
180        struct __assign<true> {
181                template<typename core_t, typename node_t>
182                static inline void result( core_t & core, const node_t * & node ) {
183                        core.previsit( node );
184                }
185        };
186
187        template<>
188        struct __assign<false> {
189                template<typename core_t, typename node_t>
190                static inline void result( core_t & core, const node_t * & node ) {
191                        node = core.previsit( node );
192                        assertf(node, "Previsit must not return NULL");
193                }
194        };
195
196        /// Used by postvisit implementation
197        /// We need to return the result unless the function
198        /// returns void, then we just return the original node
199        template<bool is_void>
200        struct __return;
201
202        template<>
203        struct __return<true> {
204                template<typename core_t, typename node_t>
205                static inline const node_t * result( core_t & core, const node_t * & node ) {
206                        core.postvisit( node );
207                        return node;
208                }
209        };
210
211        template<>
212        struct __return<false> {
213                template<typename core_t, typename node_t>
214                static inline auto result( core_t & core, const node_t * & node ) {
215                        return core.postvisit( node );
216                }
217        };
218
219        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
220        // Deep magic (a.k.a template meta programming) to make the templated visitor work
221        // Basically the goal is to make 2 previsit
222        // 1 - Use when a pass implements a valid previsit. This uses overloading which means the any overload of
223        //     'pass.previsit( node )' that compiles will be used for that node for that type
224        //     This requires that this option only compile for passes that actually define an appropriate visit.
225        //     SFINAE will make sure the compilation errors in this function don't halt the build.
226        //     See http://en.cppreference.com/w/cpp/language/sfinae for details on SFINAE
227        // 2 - Since the first implementation might not be specilizable, the second implementation exists and does nothing.
228        //     This is needed only to eliminate the need for passes to specify any kind of handlers.
229        //     The second implementation only works because it has a lower priority. This is due to the bogus last parameter.
230        //     The second implementation takes a long while the first takes an int. Since the caller always passes an literal 0
231        //     the first implementation takes priority in regards to overloading.
232        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
233        // PreVisit : may mutate the pointer passed in if the node is mutated in the previsit call
234        template<typename core_t, typename node_t>
235        static inline auto previsit( core_t & core, const node_t * & node, int ) -> decltype( core.previsit( node ), void() ) {
236                static_assert(
237                        is_valid_previsit<core_t, node_t>::value,
238                        "Previsit may not change the type of the node. It must return its paremeter or void."
239                );
240
241                __assign<
242                        std::is_void<
243                                decltype( core.previsit( node ) )
244                        >::value
245                >::result( core, node );
246        }
247
248        template<typename core_t, typename node_t>
249        static inline auto previsit( core_t &, const node_t *, long ) {}
250
251        // PostVisit : never mutates the passed pointer but may return a different node
252        template<typename core_t, typename node_t>
253        static inline auto postvisit( core_t & core, const node_t * node, int ) ->
254                decltype( core.postvisit( node ), node->accept( *(Visitor*)nullptr ) )
255        {
256                return __return<
257                        std::is_void<
258                                decltype( core.postvisit( node ) )
259                        >::value
260                >::result( core, node );
261        }
262
263        template<typename core_t, typename node_t>
264        static inline const node_t * postvisit( core_t &, const node_t * node, long ) { return node; }
265
266        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
267        // Deep magic (a.k.a template meta programming) continued
268        // To make the templated visitor be more expressive, we allow 'accessories' : classes/structs the implementation can inherit
269        // from in order to get extra functionallity for example
270        // class ErrorChecker : WithShortCircuiting { ... };
271        // Pass<ErrorChecker> checker;
272        // this would define a pass that uses the templated visitor with the additionnal feature that it has short circuiting
273        // Note that in all cases the accessories are not required but guarantee the requirements of the feature is matched
274        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
275        // For several accessories, the feature is enabled by detecting that a specific field is present
276        // Use a macro the encapsulate the logic of detecting a particular field
277        // The type is not strictly enforced but does match the accessory
278        #define FIELD_PTR( name, default_type ) \
279        template< typename core_t > \
280        static inline auto name( core_t & core, int ) -> decltype( &core.name ) { return &core.name; } \
281        \
282        template< typename core_t > \
283        static inline default_type * name( core_t &, long ) { return nullptr; }
284
285        // List of fields and their expected types
286        FIELD_PTR( typeSubs, const ast::TypeSubstitution * )
287        FIELD_PTR( stmtsToAddBefore, std::list< ast::ptr< ast::Stmt > > )
288        FIELD_PTR( stmtsToAddAfter , std::list< ast::ptr< ast::Stmt > > )
289        FIELD_PTR( declsToAddBefore, std::list< ast::ptr< ast::Decl > > )
290        FIELD_PTR( declsToAddAfter , std::list< ast::ptr< ast::Decl > > )
291        FIELD_PTR( visit_children, __pass::bool_ref )
292        FIELD_PTR( at_cleanup, __pass::at_cleanup_t )
293        FIELD_PTR( visitor, ast::Pass<core_t> * const )
294
295        // Remove the macro to make sure we don't clash
296        #undef FIELD_PTR
297
298        template< typename core_t >
299        static inline auto beginTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
300                // Stats::Heap::stacktrace_push(core_t::traceId);
301        }
302
303        template< typename core_t >
304        static inline auto endTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
305                // Stats::Heap::stacktrace_pop();
306        }
307
308        template< typename core_t >
309        static void beginTrace(core_t &, long) {}
310
311        template< typename core_t >
312        static void endTrace(core_t &, long) {}
313
314        // Allows visitor to handle an error on top-level declarations, and possibly suppress the error.
315        // If onError() returns false, the error will be ignored. By default, it returns true.
316
317        template< typename core_t >
318        static bool on_error (core_t &, ptr<Decl> &, long) { return true; }
319
320        template< typename core_t >
321        static auto on_error (core_t & core, ptr<Decl> & decl, int) -> decltype(core.on_error(decl)) {
322                return core.on_error(decl);
323        }
324
325        // Another feature of the templated visitor is that it calls beginScope()/endScope() for compound statement.
326        // All passes which have such functions are assumed desire this behaviour
327        // detect it using the same strategy
328        namespace scope {
329                template<typename core_t>
330                static inline auto enter( core_t & core, int ) -> decltype( core.beginScope(), void() ) {
331                        core.beginScope();
332                }
333
334                template<typename core_t>
335                static inline void enter( core_t &, long ) {}
336
337                template<typename core_t>
338                static inline auto leave( core_t & core, int ) -> decltype( core.endScope(), void() ) {
339                        core.endScope();
340                }
341
342                template<typename core_t>
343                static inline void leave( core_t &, long ) {}
344        } // namespace scope
345
346        // Certain passes desire an up to date symbol table automatically
347        // detect the presence of a member name `symtab` and call all the members appropriately
348        namespace symtab {
349                // Some simple scoping rules
350                template<typename core_t>
351                static inline auto enter( core_t & core, int ) -> decltype( core.symtab, void() ) {
352                        core.symtab.enterScope();
353                }
354
355                template<typename core_t>
356                static inline auto enter( core_t &, long ) {}
357
358                template<typename core_t>
359                static inline auto leave( core_t & core, int ) -> decltype( core.symtab, void() ) {
360                        core.symtab.leaveScope();
361                }
362
363                template<typename core_t>
364                static inline auto leave( core_t &, long ) {}
365
366                // The symbol table has 2 kind of functions mostly, 1 argument and 2 arguments
367                // Create macro to condense these common patterns
368                #define SYMTAB_FUNC1( func, type ) \
369                template<typename core_t> \
370                static inline auto func( core_t & core, int, type arg ) -> decltype( core.symtab.func( arg ), void() ) {\
371                        core.symtab.func( arg ); \
372                } \
373                \
374                template<typename core_t> \
375                static inline void func( core_t &, long, type ) {}
376
377                #define SYMTAB_FUNC2( func, type1, type2 ) \
378                template<typename core_t> \
379                static inline auto func( core_t & core, int, type1 arg1, type2 arg2 ) -> decltype( core.symtab.func( arg1, arg2 ), void () ) {\
380                        core.symtab.func( arg1, arg2 ); \
381                } \
382                        \
383                template<typename core_t> \
384                static inline void func( core_t &, long, type1, type2 ) {}
385
386                SYMTAB_FUNC1( addId     , const DeclWithType *  );
387                SYMTAB_FUNC1( addType   , const NamedTypeDecl * );
388                SYMTAB_FUNC1( addStruct , const StructDecl *    );
389                SYMTAB_FUNC1( addEnum   , const EnumDecl *      );
390                SYMTAB_FUNC1( addUnion  , const UnionDecl *     );
391                SYMTAB_FUNC1( addTrait  , const TraitDecl *     );
392                SYMTAB_FUNC2( addWith   , const std::vector< ptr<Expr> > &, const Decl * );
393
394                // A few extra functions have more complicated behaviour, they are hand written
395                template<typename core_t>
396                static inline auto addStructFwd( core_t & core, int, const ast::StructDecl * decl ) -> decltype( core.symtab.addStruct( decl ), void() ) {
397                        ast::StructDecl * fwd = new ast::StructDecl( decl->location, decl->name );
398                        fwd->params = decl->params;
399                        core.symtab.addStruct( fwd );
400                }
401
402                template<typename core_t>
403                static inline void addStructFwd( core_t &, long, const ast::StructDecl * ) {}
404
405                template<typename core_t>
406                static inline auto addUnionFwd( core_t & core, int, const ast::UnionDecl * decl ) -> decltype( core.symtab.addUnion( decl ), void() ) {
407                        UnionDecl * fwd = new UnionDecl( decl->location, decl->name );
408                        fwd->params = decl->params;
409                        core.symtab.addUnion( fwd );
410                }
411
412                template<typename core_t>
413                static inline void addUnionFwd( core_t &, long, const ast::UnionDecl * ) {}
414
415                template<typename core_t>
416                static inline auto addStruct( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addStruct( str ), void() ) {
417                        if ( ! core.symtab.lookupStruct( str ) ) {
418                                core.symtab.addStruct( str );
419                        }
420                }
421
422                template<typename core_t>
423                static inline void addStruct( core_t &, long, const std::string & ) {}
424
425                template<typename core_t>
426                static inline auto addUnion( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addUnion( str ), void() ) {
427                        if ( ! core.symtab.lookupUnion( str ) ) {
428                                core.symtab.addUnion( str );
429                        }
430                }
431
432                template<typename core_t>
433                static inline void addUnion( core_t &, long, const std::string & ) {}
434
435                #undef SYMTAB_FUNC1
436                #undef SYMTAB_FUNC2
437        } // namespace symtab
438
439        // Some passes need to mutate TypeDecl and properly update their pointing TypeInstType.
440        // Detect the presence of a member name `subs` and call all members appropriately
441        namespace forall {
442                // Some simple scoping rules
443                template<typename core_t>
444                static inline auto enter( core_t & core, int, const ast::FunctionType * type )
445                -> decltype( core.subs, void() ) {
446                        if ( ! type->forall.empty() ) core.subs.beginScope();
447                }
448
449                template<typename core_t>
450                static inline auto enter( core_t &, long, const ast::FunctionType * ) {}
451
452                template<typename core_t>
453                static inline auto leave( core_t & core, int, const ast::FunctionType * type )
454                -> decltype( core.subs, void() ) {
455                        if ( ! type->forall.empty() ) { core.subs.endScope(); }
456                }
457
458                template<typename core_t>
459                static inline auto leave( core_t &, long, const ast::FunctionType * ) {}
460
461                // Replaces a TypeInstType's base TypeDecl according to the table
462                template<typename core_t>
463                static inline auto replace( core_t & core, int, const ast::TypeInstType *& inst )
464                -> decltype( core.subs, void() ) {
465                        inst = ast::mutate_field(
466                                inst, &ast::TypeInstType::base, core.subs.replace( inst->base ) );
467                }
468
469                template<typename core_t>
470                static inline auto replace( core_t &, long, const ast::TypeInstType *& ) {}
471
472        } // namespace forall
473
474        // For passes that need access to the global context. Sreaches `translationUnit`
475        namespace translation_unit {
476                template<typename core_t>
477                static inline auto get_cptr( core_t & core, int )
478                                -> decltype( &core.translationUnit ) {
479                        return &core.translationUnit;
480                }
481
482                template<typename core_t>
483                static inline const TranslationUnit ** get_cptr( core_t &, long ) {
484                        return nullptr;
485                }
486        }
487
488        template<typename core_t>
489        static inline auto get_result( core_t & core, char ) -> decltype( core.result() ) {
490                return core.result();
491        }
492
493        template<typename core_t>
494        static inline auto get_result( core_t & core, int ) -> decltype( core.result ) {
495                return core.result;
496        }
497
498        template<typename core_t>
499        static inline void get_result( core_t &, long ) {}
500} // namespace __pass
501} // namespace ast
Note: See TracBrowser for help on using the repository browser.