source: src/ResolvExpr/TypeEnvironment.h @ 5c14030

new-env
Last change on this file since 5c14030 was 5c14030, checked in by Aaron Moss <a3moss@…>, 6 years ago

Persistent-array environment compiles

  • Property mode set to 100644
File size: 10.6 KB
Line 
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// TypeEnvironment.h --
8//
9// Author           : Aaron B. Moss
10// Created On       : Sun May 17 12:24:58 2015
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Fri Jun 29 16:00:00 2018
13// Update Count     : 5
14//
15
16#pragma once
17
18#include <iostream>                        // for ostream
19#include <iterator>
20#include <list>                            // for list, list<>::iterator, list<>...
21#include <map>                             // for map, map<>::value_compare
22#include <set>                             // for set
23#include <string>                          // for string
24#include <utility>                         // for pair
25#include <vector>                          // for vector
26
27#include "WidenMode.h"                 // for WidenMode
28
29#include "Common/InternedString.h"         // for interned_string
30#include "Common/PersistentDisjointSet.h"  // for PersistentDisjointSet
31#include "Common/PersistentMap.h"          // for PersistentMap
32#include "SynTree/Declaration.h"           // for TypeDecl::Data, DeclarationWit...
33#include "SynTree/SynTree.h"               // for UniqueId
34#include "SynTree/Type.h"                  // for Type, TypeInstType, Type::ForallList
35#include "SynTree/TypeSubstitution.h"      // for TypeSubstitution
36
37template< typename Pass > class PassVisitor;
38class GcTracer;
39namespace SymTab { class Indexer; }
40
41namespace ResolvExpr {
42        // adding this comparison operator significantly improves assertion resolution run time for
43        // some cases. The current resolution algorithm's speed partially depends on the order of
44        // assertions. Assertions which have fewer possible matches should appear before
45        // assertions which have more possible matches. This seems to imply that this could
46        // be further improved by providing an indexer as an additional argument and ordering based
47        // on the number of matches of the same kind (object, function) for the names of the
48        // declarations.
49        //
50        // I've seen a TU go from 54 minutes to 1 minute 34 seconds with the addition of this
51        // comparator.
52        //
53        // Note: since this compares pointers for position, minor changes in the source file that affect
54        // memory layout can alter compilation time in unpredictable ways. For example, the placement
55        // of a line directive can reorder type pointers with respect to each other so that assertions
56        // are seen in different orders, causing a potentially different number of unification calls
57        // when resolving assertions. I've seen a TU go from 36 seconds to 27 seconds by reordering
58        // line directives alone, so it would be nice to fix this comparison so that assertions compare
59        // more consistently. I've tried to modify this to compare on mangle name instead of type as
60        // the second comparator, but this causes some assertions to never be recorded. More
61        // investigation is needed.
62        struct AssertCompare {
63                bool operator()( DeclarationWithType * d1, DeclarationWithType * d2 ) const {
64                        int cmp = d1->get_name().compare( d2->get_name() );
65                        return cmp < 0 ||
66                                ( cmp == 0 && d1->get_type() < d2->get_type() );
67                }
68        };
69        struct AssertionSetValue {
70                bool isUsed;
71                // chain of Unique IDs of the assertion declarations. The first ID in the chain is the ID
72                // of an assertion on the current type, with each successive ID being the ID of an
73                // assertion pulled in by the previous ID. The last ID in the chain is the ID of the
74                // assertion that pulled in the current assertion.
75                std::list< UniqueId > idChain;
76        };
77        typedef std::map< DeclarationWithType*, AssertionSetValue, AssertCompare > AssertionSet;
78        typedef std::map< std::string, TypeDecl::Data > OpenVarSet;
79
80        void printAssertionSet( const AssertionSet &, std::ostream &, int indent = 0 );
81        void printOpenVarSet( const OpenVarSet &, std::ostream &, int indent = 0 );
82
83        /// A data structure for holding all the necessary information for a type binding
84        struct BoundType {
85                Type* type;
86                bool allowWidening;
87                TypeDecl::Data data;
88
89                BoundType() = default;
90                BoundType( TypeDecl* td ) : type{nullptr}, allowWidening{true}, data{td} {}
91                BoundType( Type* ty, bool aw, const TypeDecl::Data& td )
92                        : type{ty}, allowWidening{aw}, data{td} {}
93                BoundType( const BoundType& o )
94                        : type{maybeClone(o.type)}, allowWidening{o.allowWidening}, data{o.data} {}
95                BoundType( BoundType&& o ) = default;
96                BoundType& operator= (const BoundType& o) {
97                        if ( this == &o ) return *this;
98                        type = maybeClone( o.type );
99                        allowWidening = o.allowWidening;
100                        data = o.data;
101                        return *this;
102                }
103                BoundType& operator= (BoundType&& o) = default;
104        };
105
106        class TypeEnvironment;
107
108        /// A reference to an equivalence class that may be used to constitute one from its environment
109        class ClassRef {
110                friend TypeEnvironment;
111
112                const TypeEnvironment* env;  ///< Containing environment
113                interned_string root;        ///< Name of root type
114
115        public:
116                ClassRef() : env(nullptr), root(nullptr) {}
117                ClassRef( const TypeEnvironment* env, interned_string root ) : env(env), root(root) {}
118
119                /// Gets the root of the reference equivalence class;
120                interned_string get_root() const { return root; }
121
122                /// Ensures that root is still the representative element of this typeclass;
123                /// undefined behaviour if called without referenced typeclass; returns new root
124                inline interned_string update_root();
125
126                /// Gets the type variables of the referenced equivalence class, empty list for none
127                template<typename T = std::vector<interned_string>>
128                inline T get_vars() const;
129
130                /// Gets the bound type information of the referenced equivalence class, default if none
131                inline BoundType get_bound() const;
132
133                // Check that there is a referenced typeclass
134                explicit operator bool() const { return env != nullptr; }
135
136                bool operator== (const ClassRef& o) const { return env == o.env && root == o.root; }
137                bool operator!= (const ClassRef& o) const { return !(*this == o); }
138        };
139
140        class TypeEnvironment {
141                friend ClassRef;
142
143                /// Backing storage for equivalence classes
144                using Classes = PersistentDisjointSet<interned_string>;
145                /// Type bindings included in this environment (from class root)
146                using Bindings = PersistentMap<interned_string, BoundType>;
147
148                /// Sets of equivalent type variables, stored by name
149                Classes* classes;
150                /// Bindings from roots of equivalence classes to type binding information.
151                /// All roots have a binding so that the list of classes can be reconstituted, though these
152                /// may be null.
153                Bindings* bindings;
154
155                /// Merges the classes rooted at root1 and root2, returning a pair containing the root and
156                /// child of the bound class. Does not check for validity of merge.
157                std::pair<interned_string, interned_string> mergeClasses( 
158                        interned_string root1, interned_string root2 );
159
160        public:
161                class iterator : public std::iterator<
162                                std::forward_iterator_tag, 
163                                ClassRef, 
164                                std::iterator_traits<Bindings::iterator>::difference_type,
165                                ClassRef,
166                                ClassRef> {
167                        friend TypeEnvironment;
168                       
169                        const TypeEnvironment* env;
170                        Bindings::iterator it;
171
172                        iterator(const TypeEnvironment* e, Bindings::iterator&& i) : env(e), it(std::move(i)) {}
173
174                        ClassRef ref() const { return { env, it->first }; }
175                public:
176                        iterator() = default;
177
178                        reference operator* () { return ref(); }
179                        pointer operator-> () { return ref(); }
180
181                        iterator& operator++ () { ++it; return *this; }
182                        iterator operator++ (int) { iterator tmp = *this; ++(*this); return tmp; }
183
184                        bool operator== (const iterator& o) const { return env == o.env && it == o.it; }
185                        bool operator!= (const iterator& o) const { return !(*this == o); }
186                };
187
188                /// Finds a reference to the class containing `var`, invalid if none such.
189                /// returned root variable will be valid regardless
190                ClassRef lookup( interned_string var ) const;
191
192                /// Binds a type variable to a type; returns false if fails
193                bool bindVar( TypeInstType* typeInst, Type* bindTo, const TypeDecl::Data& data, 
194                        AssertionSet& need, AssertionSet& have, const OpenVarSet& openVars, 
195                        WidenMode widenMode, const SymTab::Indexer& indexer );
196               
197                /// Binds two type variables together; returns false if fails
198                bool bindVarToVar( TypeInstType* var1, TypeInstType* var2, const TypeDecl::Data& data, 
199                        AssertionSet& need, AssertionSet& have, const OpenVarSet& openVars, 
200                        WidenMode widenMode, const SymTab::Indexer& indexer );
201
202        public:
203                TypeEnvironment() : classes{ new Classes{} }, bindings{ new Bindings{} } {}
204
205                void add( const Type::ForallList &tyDecls );
206                void add( const TypeSubstitution & sub );
207                template< typename SynTreeClass > int apply( SynTreeClass *&type ) const;
208                template< typename SynTreeClass > int applyFree( SynTreeClass *&type ) const;
209                void makeSubstitution( TypeSubstitution &result ) const;
210                bool isEmpty() const { return classes->empty(); }
211                void print( std::ostream &os, Indenter indent = {} ) const;
212       
213                /// Combines two environments without checking invariants.
214                /// Caller should ensure environments do not share type variables.
215                void simpleCombine( const TypeEnvironment &second );
216       
217                void extractOpenVars( OpenVarSet &openVars ) const;
218                TypeEnvironment *clone() const { return new TypeEnvironment( *this ); }
219
220                /// Iteratively adds the environment of a new actual (with allowWidening = false),
221                /// and extracts open variables.
222                void addActual( const TypeEnvironment& actualEnv, OpenVarSet& openVars );
223
224                /// Disallows widening for all bindings in the environment
225                void forbidWidening();
226
227                iterator begin() const { return { this, bindings->begin() }; }
228                iterator end() const { return { this, bindings->end() }; }
229        };
230
231        interned_string ClassRef::update_root() { return root = env->classes->find( root ); }
232
233        template<typename T>
234        T ClassRef::get_vars() const {
235                T vars;
236                if ( ! env->classes->count( root ) ) return vars;
237                env->classes->for_class( root, [&vars]( interned_string var ) {
238                        vars.insert( vars.end(), var );
239                } );
240                return vars;
241        }
242
243        BoundType ClassRef::get_bound() const {
244                return env->bindings->get_or_default( root, BoundType{} );
245        }
246
247        template< typename SynTreeClass >
248        int TypeEnvironment::apply( SynTreeClass *&type ) const {
249                TypeSubstitution sub;
250                makeSubstitution( sub );
251                return sub.apply( type );
252        }
253
254        template< typename SynTreeClass >
255        int TypeEnvironment::applyFree( SynTreeClass *&type ) const {
256                TypeSubstitution sub;
257                makeSubstitution( sub );
258                return sub.applyFree( type );
259        }
260
261        std::ostream & operator<<( std::ostream & out, const TypeEnvironment & env );
262
263        PassVisitor<GcTracer> & operator<<( PassVisitor<GcTracer> & gc, const TypeEnvironment & env );
264} // namespace ResolvExpr
265
266// Local Variables: //
267// tab-width: 4 //
268// mode: c++ //
269// compile-command: "make install" //
270// End: //
Note: See TracBrowser for help on using the repository browser.