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