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