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