]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/compiler.cpp
Use default member initializers for simple types
[libs/gl.git] / source / glsl / compiler.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/utils.h>
4 #include "builtin.h"
5 #include "compiler.h"
6 #include "debug.h"
7 #include "deviceinfo.h"
8 #include "error.h"
9 #include "finalize.h"
10 #include "generate.h"
11 #include "glsl_error.h"
12 #include "modulecache.h"
13 #include "optimize.h"
14 #include "output.h"
15 #include "resolve.h"
16 #include "spirv.h"
17 #include "validate.h"
18
19 #undef interface
20
21 using namespace std;
22
23 namespace Msp {
24 namespace GL {
25 namespace SL {
26
27 Compiler::Compiler():
28         features(DeviceInfo::get_global().glsl_features)
29 { }
30
31 Compiler::Compiler(const Features &f):
32         features(f)
33 { }
34
35 Compiler::~Compiler()
36 {
37         delete module;
38 }
39
40 void Compiler::clear()
41 {
42         delete module;
43         module = new Module();
44         imported_names.clear();
45         module->source_map.set_name(0, "<generated>");
46 }
47
48 void Compiler::set_source(const string &source, const string &src_name)
49 {
50         clear();
51         imported_names.push_back(src_name);
52         ModuleCache mod_cache(0);
53         append_module(mod_cache.add_module(source, src_name), mod_cache);
54 }
55
56 void Compiler::load_source(IO::Base &io, DataFile::Collection *res, const string &src_name)
57 {
58         clear();
59         imported_names.push_back(src_name);
60         ModuleCache mod_cache(res);
61         append_module(mod_cache.add_module(io, src_name), mod_cache);
62 }
63
64 void Compiler::load_source(IO::Base &io, const string &src_name)
65 {
66         load_source(io, 0, src_name);
67 }
68
69 void Compiler::specialize(const map<string, int> &sv)
70 {
71         specialized = true;
72         spec_values = sv;
73 }
74
75 void Compiler::compile(Mode mode)
76 {
77         if(specialized && mode!=PROGRAM)
78                 throw invalid_operation("Compiler::compile");
79
80         for(Stage &s: module->stages)
81                 generate(s);
82         ConstantIdAssigner().apply(*module, features);
83
84         for(Stage &s: module->stages)
85                 validate(s);
86         GlobalInterfaceValidator().apply(*module);
87
88         bool valid = true;
89         for(Stage &s: module->stages)
90                 if(!check_errors(s))
91                         valid = false;
92         if(!valid)
93                 throw invalid_shader_source(get_diagnostics());
94
95         if(specialized)
96         {
97                 for(Stage &s: module->stages)
98                         ConstantSpecializer().apply(s, spec_values);
99         }
100         for(auto i=module->stages.begin(); i!=module->stages.end(); )
101         {
102                 OptimizeResult result = optimize(*i);
103                 if(result==REDO_PREVIOUS)
104                         i = module->stages.begin();
105                 else if(result!=REDO_STAGE)
106                         ++i;
107         }
108
109         LocationAllocator().apply(*module, features);
110         for(Stage &s: module->stages)
111                 finalize(s, mode);
112
113         compiled = true;
114 }
115
116 string Compiler::get_combined_glsl() const
117 {
118         if(!compiled)
119                 throw invalid_operation("Compiler::get_combined_glsl");
120
121         string glsl;
122
123         unsigned source_count = module->source_map.get_count();
124         for(unsigned i=1; i<source_count; ++i)
125                 glsl += format("#pragma MSP source(%d, \"%s\")\n", i, module->source_map.get_name(i));
126         for(Stage &s: module->stages)
127         {
128                 glsl += format("#pragma MSP stage(%s)\n", Stage::get_stage_name(s.type));
129                 glsl += Formatter().apply(s);
130                 glsl += '\n';
131         }
132
133         return glsl;
134 }
135
136 vector<Stage::Type> Compiler::get_stages() const
137 {
138         vector<Stage::Type> stage_types;
139         stage_types.reserve(module->stages.size());
140         for(const Stage &s: module->stages)
141                 stage_types.push_back(s.type);
142         return stage_types;
143 }
144
145 string Compiler::get_stage_glsl(Stage::Type stage_type) const
146 {
147         if(!compiled)
148                 throw invalid_operation("Compiler::get_stage_glsl");
149         auto i = find_member(module->stages, stage_type, &Stage::type);
150         if(i!=module->stages.end())
151                 return Formatter().apply(*i);
152         throw key_error(Stage::get_stage_name(stage_type));
153 }
154
155 vector<uint32_t> Compiler::get_combined_spirv() const
156 {
157         if(!compiled)
158                 throw invalid_operation("Compiler::get_combined_spirv");
159         SpirVGenerator gen;
160         gen.apply(*module);
161         return gen.get_code();
162 }
163
164 const map<string, unsigned> &Compiler::get_vertex_attributes() const
165 {
166         if(!compiled)
167                 throw invalid_operation("Compiler::get_vertex_attributes");
168         auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
169         if(i!=module->stages.end())
170                 return i->locations;
171         throw invalid_operation("Compiler::get_vertex_attributes");
172 }
173
174 const map<string, unsigned> &Compiler::get_fragment_outputs() const
175 {
176         if(!compiled)
177                 throw invalid_operation("Compiler::get_fragment_outputs");
178         auto i = find_member(module->stages, Stage::FRAGMENT, &Stage::type);
179         if(i!=module->stages.end())
180                 return i->locations;
181         throw invalid_operation("Compiler::get_fragment_outputs");
182 }
183
184 const map<string, unsigned> &Compiler::get_texture_bindings() const
185 {
186         if(!compiled)
187                 throw invalid_operation("Compiler::get_texture_bindings");
188         return module->shared.texture_bindings;
189 }
190
191 const map<string, unsigned> &Compiler::get_uniform_block_bindings() const
192 {
193         if(!compiled)
194                 throw invalid_operation("Compiler::get_uniform_block_bindings");
195         return module->shared.uniform_block_bindings;
196 }
197
198 const SourceMap &Compiler::get_source_map() const
199 {
200         return module->source_map;
201 }
202
203 string Compiler::get_stage_debug(Stage::Type stage_type) const
204 {
205         auto i = find_member(module->stages, stage_type, &Stage::type);
206         if(i!=module->stages.end())
207                 return DumpTree().apply(*i);
208         throw key_error(Stage::get_stage_name(stage_type));
209 }
210
211 string Compiler::get_diagnostics() const
212 {
213         string combined;
214         for(const Stage &s: module->stages)
215                 for(const Diagnostic &d: s.diagnostics)
216                         if(d.source!=INTERNAL_SOURCE)
217                                 append(combined, "\n", format("%s:%d: %s", module->source_map.get_name(d.source), d.line, d.message));
218         return combined;
219 }
220
221 void Compiler::append_module(const Module &mod, ModuleCache &mod_cache)
222 {
223         module->source_map.merge_from(mod.source_map);
224
225         vector<Import *> imports;
226         for(const RefPtr<Statement> &s: mod.shared.content.body)
227                 if(Import *imp = dynamic_cast<Import *>(s.get()))
228                         imports.push_back(imp);
229         for(Import *i: imports)
230                 import(mod_cache, i->module);
231
232         append_stage(mod.shared);
233         for(const Stage &s: mod.stages)
234                 append_stage(s);
235 }
236
237 void Compiler::append_stage(const Stage &stage)
238 {
239         Stage *target = 0;
240         if(stage.type==Stage::SHARED)
241                 target = &module->shared;
242         else
243         {
244                 auto i = find_if(module->stages, [&stage](const Stage &s){ return s.type>=stage.type; });
245                 if(i==module->stages.end() || i->type>stage.type)
246                 {
247                         auto j = module->stages.insert(i, stage.type);
248                         if(i!=module->stages.end())
249                                 i->previous = &*j;
250                         i = j;
251                         if(i!=module->stages.begin())
252                                 i->previous = &*--j;
253                 }
254
255                 target = &*i;
256         }
257
258         if(stage.required_features.glsl_version>target->required_features.glsl_version)
259                 target->required_features.glsl_version = stage.required_features.glsl_version;
260         for(const RefPtr<Statement> &s: stage.content.body)
261                 if(!dynamic_cast<Import *>(s.get()))
262                         target->content.body.push_back(s);
263 }
264
265 void Compiler::import(ModuleCache &mod_cache, const string &name)
266 {
267         if(find(imported_names, name)!=imported_names.end())
268                 return;
269         imported_names.push_back(name);
270
271         append_module(mod_cache.get_module(name), mod_cache);
272 }
273
274 void Compiler::generate(Stage &stage)
275 {
276         stage.required_features.target_api = features.target_api;
277         if(module->shared.required_features.glsl_version>stage.required_features.glsl_version)
278                 stage.required_features.glsl_version = module->shared.required_features.glsl_version;
279
280         inject_block(stage.content, module->shared.content);
281         if(const Stage *builtins = get_builtins(stage.type))
282                 inject_block(stage.content, builtins->content);
283         if(const Stage *builtins = get_builtins(Stage::SHARED))
284                 inject_block(stage.content, builtins->content);
285
286         // Initial resolving pass
287         resolve(stage);
288
289         /* All variables local to a stage have been resolved.  Resolve non-local
290         variables through interfaces. */
291         InterfaceGenerator().apply(stage);
292         resolve(stage, RESOLVE_BLOCKS|RESOLVE_TYPES|RESOLVE_VARIABLES);
293 }
294
295 template<typename T>
296 bool Compiler::resolve(Stage &stage, unsigned &flags, unsigned bit)
297 {
298         if(!(flags&bit))
299                 return false;
300
301         flags &= ~bit;
302         return T().apply(stage);
303 }
304
305 void Compiler::resolve(Stage &stage, unsigned flags)
306 {
307         while(flags)
308         {
309                 if(resolve<BlockHierarchyResolver>(stage, flags, RESOLVE_BLOCKS))
310                         ;
311                 else if(resolve<TypeResolver>(stage, flags, RESOLVE_TYPES))
312                         flags |= RESOLVE_BLOCKS|RESOLVE_VARIABLES|RESOLVE_EXPRESSIONS;
313                 else if(resolve<VariableResolver>(stage, flags, RESOLVE_VARIABLES))
314                         flags |= RESOLVE_EXPRESSIONS;
315                 else if(resolve<FunctionResolver>(stage, flags, RESOLVE_FUNCTIONS))
316                         flags |= RESOLVE_EXPRESSIONS;
317                 else if(resolve<ExpressionResolver>(stage, flags, RESOLVE_EXPRESSIONS))
318                         flags |= RESOLVE_VARIABLES|RESOLVE_FUNCTIONS;
319         }
320 }
321
322 void Compiler::validate(Stage &stage)
323 {
324         DeclarationValidator().apply(stage);
325         IdentifierValidator().apply(stage);
326         ReferenceValidator().apply(stage);
327         ExpressionValidator().apply(stage);
328         FlowControlValidator().apply(stage);
329         StageInterfaceValidator().apply(stage);
330 }
331
332 bool Compiler::check_errors(Stage &stage)
333 {
334         stable_sort(stage.diagnostics, &diagnostic_line_order);
335         return !any_of(stage.diagnostics.begin(), stage.diagnostics.end(),
336                 [](const Diagnostic &d){ return d.severity==Diagnostic::ERR; });
337 }
338
339 bool Compiler::diagnostic_line_order(const Diagnostic &diag1, const Diagnostic &diag2)
340 {
341         if(diag1.provoking_source!=diag2.provoking_source)
342         {
343                 // Sort builtins first and imported modules according to import order.
344                 if(diag1.provoking_source<=BUILTIN_SOURCE)
345                         return diag1.provoking_source<diag2.provoking_source;
346                 else if(diag2.provoking_source<=BUILTIN_SOURCE)
347                         return false;
348                 else
349                         return diag1.provoking_source>diag2.provoking_source;
350         }
351         return diag1.provoking_line<diag2.provoking_line;
352 }
353
354 Compiler::OptimizeResult Compiler::optimize(Stage &stage)
355 {
356         if(ConstantFolder().apply(stage))
357                 resolve(stage, RESOLVE_EXPRESSIONS);
358         ConstantConditionEliminator().apply(stage);
359
360         bool any_inlined = false;
361         if(FunctionInliner().apply(stage))
362         {
363                 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
364                 any_inlined = true;
365         }
366         if(ExpressionInliner().apply(stage))
367         {
368                 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
369                 any_inlined = true;
370         }
371
372         /* Removing variables or functions may cause things from the previous stage
373         to become unused. */
374         bool any_removed = UnreachableCodeRemover().apply(stage);
375         any_removed |= UnusedVariableRemover().apply(stage);
376         any_removed |= UnusedFunctionRemover().apply(stage);
377         any_removed |= UnusedTypeRemover().apply(stage);
378
379         return any_removed ? REDO_PREVIOUS : any_inlined ? REDO_STAGE : NEXT_STAGE;
380 }
381
382 void Compiler::finalize(Stage &stage, Mode mode)
383 {
384         if(mode==PROGRAM)
385         {
386                 LegacyConverter().apply(stage, features);
387                 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS);
388                 PrecisionConverter().apply(stage);
389         }
390         else if(mode==SPIRV)
391                 StructOrganizer().apply(stage);
392
393         // Collect bindings from all stages into the shared stage's maps
394         module->shared.texture_bindings.insert(stage.texture_bindings.begin(), stage.texture_bindings.end());
395         module->shared.uniform_block_bindings.insert(stage.uniform_block_bindings.begin(), stage.uniform_block_bindings.end());
396 }
397
398 void Compiler::inject_block(Block &target, const Block &source)
399 {
400         auto insert_point = target.body.begin();
401         for(const RefPtr<Statement> &s: source.body)
402                 target.body.insert(insert_point, s->clone());
403 }
404
405 } // namespace SL
406 } // namespace GL
407 } // namespace Msp