source: src/AST/Pass.proto.hpp @ 90320ac

Last change on this file since 90320ac was 90320ac, checked in by Andrew Beach <ajbeach@…>, 3 months ago

Clean-up in the Pass template around call_accept. Removed overloads that no longer contain unique behaviour. Redundent early exits have been removed. Updated the names and removed redundent checks following up the result* type update. New constructors for the delta helper type show how the data is actually used. The differs functions are unused (that value is stored in the result* types).

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