source: src/AST/Pass.proto.hpp @ 38093ae

Last change on this file since 38093ae was 7a36848, checked in by Andrew Beach <ajbeach@…>, 5 weeks ago

Further Pass template clean-up, reimplementing the translation unit getter with the standard tools. The only time we needed a mutable TranslationUnit/TranslationGlobal? it was implemented manually anyways.

  • Property mode set to 100644
File size: 18.0 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 nullptr." );
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 )
312FIELD_PTR( translationUnit, const TranslationUnit * )
313
314// Remove the macro to make sure we don't clash
315#undef FIELD_PTR
316
317template< typename core_t >
318static inline auto beginTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
319        // Stats::Heap::stacktrace_push(core_t::traceId);
320}
321
322template< typename core_t >
323static inline auto endTrace(core_t &, int) -> decltype( core_t::traceId, void() ) {
324        // Stats::Heap::stacktrace_pop();
325}
326
327template< typename core_t >
328static void beginTrace(core_t &, long) {}
329
330template< typename core_t >
331static void endTrace(core_t &, long) {}
332
333// Allows visitor to handle an error on top-level declarations, and possibly suppress the error.
334// If on_error() returns false, the error will be ignored. By default, it returns true.
335
336template< typename core_t >
337static bool on_error (core_t &, ptr<Decl> &, long) { return true; }
338
339template< typename core_t >
340static auto on_error (core_t & core, ptr<Decl> & decl, int) -> decltype(core.on_error(decl)) {
341        return core.on_error(decl);
342}
343
344template< typename core_t, typename node_t >
345static auto make_location_guard( core_t & core, node_t * node, int )
346                -> decltype( node->location, ValueGuardPtr<const CodeLocation *>( &core.location ) ) {
347        ValueGuardPtr<const CodeLocation *> guard( &core.location );
348        core.location = &node->location;
349        return guard;
350}
351
352template< typename core_t, typename node_t >
353static auto make_location_guard( core_t &, node_t *, long ) -> int {
354        return 0;
355}
356
357// Another feature of the templated visitor is that it calls beginScope()/endScope() for compound statement.
358// All passes which have such functions are assumed desire this behaviour
359// detect it using the same strategy
360namespace scope {
361        template<typename core_t>
362        static inline auto enter( core_t & core, int ) -> decltype( core.beginScope(), void() ) {
363                core.beginScope();
364        }
365
366        template<typename core_t>
367        static inline void enter( core_t &, long ) {}
368
369        template<typename core_t>
370        static inline auto leave( core_t & core, int ) -> decltype( core.endScope(), void() ) {
371                core.endScope();
372        }
373
374        template<typename core_t>
375        static inline void leave( core_t &, long ) {}
376} // namespace scope
377
378// Certain passes desire an up to date symbol table automatically
379// detect the presence of a member name `symtab` and call all the members appropriately
380namespace symtab {
381        // Some simple scoping rules
382        template<typename core_t>
383        static inline auto enter( core_t & core, int ) -> decltype( core.symtab, void() ) {
384                core.symtab.enterScope();
385        }
386
387        template<typename core_t>
388        static inline auto enter( core_t &, long ) {}
389
390        template<typename core_t>
391        static inline auto leave( core_t & core, int ) -> decltype( core.symtab, void() ) {
392                core.symtab.leaveScope();
393        }
394
395        template<typename core_t>
396        static inline auto leave( core_t &, long ) {}
397
398        // The symbol table has 2 kind of functions mostly, 1 argument and 2 arguments
399        // Create macro to condense these common patterns
400        #define SYMTAB_FUNC1( func, type ) \
401        template<typename core_t> \
402        static inline auto func( core_t & core, int, type arg ) -> decltype( core.symtab.func( arg ), void() ) {\
403                core.symtab.func( arg ); \
404        } \
405        \
406        template<typename core_t> \
407        static inline void func( core_t &, long, type ) {}
408
409        #define SYMTAB_FUNC2( func, type1, type2 ) \
410        template<typename core_t> \
411        static inline auto func( core_t & core, int, type1 arg1, type2 arg2 ) -> decltype( core.symtab.func( arg1, arg2 ), void () ) {\
412                core.symtab.func( arg1, arg2 ); \
413        } \
414        \
415        template<typename core_t> \
416        static inline void func( core_t &, long, type1, type2 ) {}
417
418        SYMTAB_FUNC1( addId     , const DeclWithType *  );
419        SYMTAB_FUNC1( addType   , const NamedTypeDecl * );
420        SYMTAB_FUNC1( addStruct , const StructDecl *    );
421        SYMTAB_FUNC1( addEnum   , const EnumDecl *      );
422        SYMTAB_FUNC1( addUnion  , const UnionDecl *     );
423        SYMTAB_FUNC1( addTrait  , const TraitDecl *     );
424        SYMTAB_FUNC2( addWith   , const std::vector< ptr<Expr> > &, const Decl * );
425
426        // A few extra functions have more complicated behaviour, they are hand written
427        template<typename core_t>
428        static inline auto addStructFwd( core_t & core, int, const ast::StructDecl * decl ) -> decltype( core.symtab.addStruct( decl ), void() ) {
429                ast::StructDecl * fwd = new ast::StructDecl( decl->location, decl->name );
430                for ( const auto & param : decl->params ) {
431                        fwd->params.push_back( deepCopy( param.get() ) );
432                }
433                core.symtab.addStruct( fwd );
434        }
435
436        template<typename core_t>
437        static inline void addStructFwd( core_t &, long, const ast::StructDecl * ) {}
438
439        template<typename core_t>
440        static inline auto addUnionFwd( core_t & core, int, const ast::UnionDecl * decl ) -> decltype( core.symtab.addUnion( decl ), void() ) {
441                ast::UnionDecl * fwd = new ast::UnionDecl( decl->location, decl->name );
442                for ( const auto & param : decl->params ) {
443                        fwd->params.push_back( deepCopy( param.get() ) );
444                }
445                core.symtab.addUnion( fwd );
446        }
447
448        template<typename core_t>
449        static inline void addUnionFwd( core_t &, long, const ast::UnionDecl * ) {}
450
451        template<typename core_t>
452        static inline auto addStructId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addStructId( str ), void() ) {
453                if ( ! core.symtab.lookupStruct( str ) ) {
454                        core.symtab.addStructId( str );
455                }
456        }
457
458        template<typename core_t>
459        static inline void addStructId( core_t &, long, const std::string & ) {}
460
461        template<typename core_t>
462        static inline auto addUnionId( core_t & core, int, const std::string & str ) -> decltype( core.symtab.addUnionId( str ), void() ) {
463                if ( ! core.symtab.lookupUnion( str ) ) {
464                        core.symtab.addUnionId( str );
465                }
466        }
467
468        template<typename core_t>
469        static inline void addUnionId( core_t &, long, const std::string & ) {}
470
471        #undef SYMTAB_FUNC1
472        #undef SYMTAB_FUNC2
473} // namespace symtab
474
475// Some passes need to mutate TypeDecl and properly update their pointing TypeInstType.
476// Detect the presence of a member name `subs` and call all members appropriately
477namespace forall {
478        // Some simple scoping rules
479        template<typename core_t>
480        static inline auto enter( core_t & core, int, const ast::FunctionType * type )
481                        -> decltype( core.subs, void() ) {
482                if ( ! type->forall.empty() ) core.subs.beginScope();
483        }
484
485        template<typename core_t>
486        static inline auto enter( core_t &, long, const ast::FunctionType * ) {}
487
488        template<typename core_t>
489        static inline auto leave( core_t & core, int, const ast::FunctionType * type )
490                        -> decltype( core.subs, void() ) {
491                if ( ! type->forall.empty() ) { core.subs.endScope(); }
492        }
493
494        template<typename core_t>
495        static inline auto leave( core_t &, long, const ast::FunctionType * ) {}
496
497        // Replaces a TypeInstType's base TypeDecl according to the table
498        template<typename core_t>
499        static inline auto replace( core_t & core, int, const ast::TypeInstType *& inst )
500                        -> decltype( core.subs, void() ) {
501                inst = ast::mutate_field(
502                        inst, &ast::TypeInstType::base, core.subs.replace( inst->base ) );
503        }
504
505        template<typename core_t>
506        static inline auto replace( core_t &, long, const ast::TypeInstType *& ) {}
507} // namespace forall
508
509// For passes, usually utility passes, that have a result.
510namespace result {
511        template<typename core_t>
512        static inline auto get( core_t & core, char ) -> decltype( core.result() ) {
513                return core.result();
514        }
515
516        template<typename core_t>
517        static inline auto get( core_t & core, int ) -> decltype( core.result ) {
518                return core.result;
519        }
520
521        template<typename core_t>
522        static inline void get( core_t &, long ) {}
523}
524
525} // namespace ast::__pass
526
527#undef __pedantic_pass_assertf
528#undef __pedantic_pass_assert
Note: See TracBrowser for help on using the repository browser.