1 #include <msp/core/algorithm.h>
2 #include <msp/strings/format.h>
3 #include <msp/strings/utils.h>
10 #include "glsl_error.h"
11 #include "modulecache.h"
26 Compiler::Compiler(const Features &f):
35 void Compiler::clear()
38 module = new Module();
39 imported_names.clear();
40 module->source_map.set_name(0, "<generated>");
43 void Compiler::set_source(const string &source, const string &src_name)
46 imported_names.push_back(src_name);
47 ModuleCache mod_cache(0);
48 append_module(mod_cache.add_module(source, src_name), mod_cache);
51 void Compiler::load_source(IO::Base &io, DataFile::Collection *res, const string &src_name)
54 imported_names.push_back(src_name);
55 ModuleCache mod_cache(res);
56 append_module(mod_cache.add_module(io, src_name), mod_cache);
59 void Compiler::load_source(IO::Base &io, const string &src_name)
61 load_source(io, 0, src_name);
64 void Compiler::specialize(const map<string, int> &sv)
70 void Compiler::compile(Mode mode)
72 if(specialized && mode!=PROGRAM)
73 throw invalid_operation("Compiler::compile");
75 for(Stage &s: module->stages)
77 ConstantIdAssigner().apply(*module, features);
78 LocationAllocator().apply(*module, features, false);
80 for(Stage &s: module->stages)
82 GlobalInterfaceValidator().apply(*module);
85 for(Stage &s: module->stages)
89 throw invalid_shader_source(get_diagnostics());
93 for(Stage &s: module->stages)
94 ConstantSpecializer().apply(s, spec_values);
96 for(auto i=module->stages.begin(); i!=module->stages.end(); )
98 OptimizeResult result = optimize(*i);
99 if(result==REDO_PREVIOUS)
100 i = module->stages.begin();
101 else if(result!=REDO_STAGE)
105 for(Stage &s: module->stages)
107 StructuralFeatureConverter().apply(s, features);
108 resolve(s, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS);
110 LocationAllocator().apply(*module, features);
111 for(Stage &s: module->stages)
117 string Compiler::get_combined_glsl() const
120 throw invalid_operation("Compiler::get_combined_glsl");
124 unsigned source_count = module->source_map.get_count();
125 for(unsigned i=1; i<source_count; ++i)
126 glsl += format("#pragma MSP source(%d, \"%s\")\n", i, module->source_map.get_name(i));
127 for(Stage &s: module->stages)
129 glsl += format("#pragma MSP stage(%s)\n", Stage::get_stage_name(s.type));
130 glsl += Formatter().apply(s);
137 vector<Stage::Type> Compiler::get_stages() const
139 vector<Stage::Type> stage_types;
140 stage_types.reserve(module->stages.size());
141 for(const Stage &s: module->stages)
142 stage_types.push_back(s.type);
146 string Compiler::get_stage_glsl(Stage::Type stage_type) const
149 throw invalid_operation("Compiler::get_stage_glsl");
150 auto i = find_member(module->stages, stage_type, &Stage::type);
151 if(i!=module->stages.end())
152 return Formatter().apply(*i);
153 throw key_error(Stage::get_stage_name(stage_type));
156 vector<uint32_t> Compiler::get_combined_spirv() const
159 throw invalid_operation("Compiler::get_combined_spirv");
162 return gen.get_code();
165 const map<string, unsigned> &Compiler::get_vertex_attributes() const
168 throw invalid_operation("Compiler::get_vertex_attributes");
169 auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
170 if(i!=module->stages.end())
172 throw invalid_operation("Compiler::get_vertex_attributes");
175 const map<string, unsigned> &Compiler::get_fragment_outputs() const
178 throw invalid_operation("Compiler::get_fragment_outputs");
179 auto i = find_member(module->stages, Stage::FRAGMENT, &Stage::type);
180 if(i!=module->stages.end())
182 throw invalid_operation("Compiler::get_fragment_outputs");
185 const map<string, unsigned> &Compiler::get_texture_bindings() const
188 throw invalid_operation("Compiler::get_texture_bindings");
189 return module->shared.texture_bindings;
192 const map<string, unsigned> &Compiler::get_uniform_block_bindings() const
195 throw invalid_operation("Compiler::get_uniform_block_bindings");
196 return module->shared.uniform_block_bindings;
199 unsigned Compiler::get_n_clip_distances() const
202 throw invalid_operation("Compiler::get_n_clip_distances");
203 auto i = find_member(module->stages, Stage::VERTEX, &Stage::type);
204 return (i!=module->stages.end() ? i->n_clip_distances : 0);
207 const SourceMap &Compiler::get_source_map() const
209 return module->source_map;
212 string Compiler::get_stage_debug(Stage::Type stage_type) const
214 auto i = find_member(module->stages, stage_type, &Stage::type);
215 if(i!=module->stages.end())
216 return DumpTree().apply(*i);
217 throw key_error(Stage::get_stage_name(stage_type));
220 string Compiler::get_diagnostics() const
223 for(const Stage &s: module->stages)
224 for(const Diagnostic &d: s.diagnostics)
225 if(d.source!=INTERNAL_SOURCE)
226 append(combined, "\n", format("%s:%d: %s", module->source_map.get_name(d.source), d.line, d.message));
230 void Compiler::append_module(const Module &mod, ModuleCache &mod_cache)
232 module->source_map.merge_from(mod.source_map);
234 vector<Import *> imports;
235 for(const RefPtr<Statement> &s: mod.shared.content.body)
236 if(Import *imp = dynamic_cast<Import *>(s.get()))
237 imports.push_back(imp);
238 for(Import *i: imports)
239 import(mod_cache, i->module);
241 append_stage(mod.shared);
242 for(const Stage &s: mod.stages)
246 void Compiler::append_stage(const Stage &stage)
249 if(stage.type==Stage::SHARED)
250 target = &module->shared;
253 auto i = find_if(module->stages, [&stage](const Stage &s){ return s.type>=stage.type; });
254 if(i==module->stages.end() || i->type>stage.type)
256 auto j = module->stages.insert(i, stage.type);
257 if(i!=module->stages.end())
260 if(i!=module->stages.begin())
267 if(stage.required_features.glsl_version>target->required_features.glsl_version)
268 target->required_features.glsl_version = stage.required_features.glsl_version;
269 for(const RefPtr<Statement> &s: stage.content.body)
270 if(!dynamic_cast<Import *>(s.get()))
271 target->content.body.push_back(s);
274 void Compiler::import(ModuleCache &mod_cache, const string &name)
276 if(find(imported_names, name)!=imported_names.end())
278 imported_names.push_back(name);
280 append_module(mod_cache.get_module(name), mod_cache);
283 void Compiler::generate(Stage &stage)
285 stage.required_features.target_api = features.target_api;
286 if(module->shared.required_features.glsl_version>stage.required_features.glsl_version)
287 stage.required_features.glsl_version = module->shared.required_features.glsl_version;
289 inject_block(stage.content, module->shared.content);
290 if(const Stage *builtins = get_builtins(stage.type))
291 inject_block(stage.content, builtins->content);
292 if(const Stage *builtins = get_builtins(Stage::SHARED))
293 inject_block(stage.content, builtins->content);
295 // Initial resolving pass
298 /* All variables local to a stage have been resolved. Resolve non-local
299 variables through interfaces. */
300 InterfaceGenerator().apply(stage);
301 resolve(stage, RESOLVE_BLOCKS|RESOLVE_TYPES|RESOLVE_VARIABLES);
305 bool Compiler::resolve(Stage &stage, unsigned &flags, unsigned bit)
311 return T().apply(stage);
314 void Compiler::resolve(Stage &stage, unsigned flags)
318 if(resolve<BlockHierarchyResolver>(stage, flags, RESOLVE_BLOCKS))
320 else if(resolve<TypeResolver>(stage, flags, RESOLVE_TYPES))
321 flags |= RESOLVE_BLOCKS|RESOLVE_VARIABLES|RESOLVE_EXPRESSIONS;
322 else if(resolve<VariableResolver>(stage, flags, RESOLVE_VARIABLES))
323 flags |= RESOLVE_EXPRESSIONS;
324 else if(resolve<FunctionResolver>(stage, flags, RESOLVE_FUNCTIONS))
325 flags |= RESOLVE_EXPRESSIONS;
326 else if(resolve<ExpressionResolver>(stage, flags, RESOLVE_EXPRESSIONS))
327 flags |= RESOLVE_VARIABLES|RESOLVE_FUNCTIONS;
331 void Compiler::validate(Stage &stage)
333 DeclarationValidator().apply(stage, features);
334 IdentifierValidator().apply(stage);
335 ReferenceValidator().apply(stage);
336 ExpressionValidator().apply(stage);
337 FlowControlValidator().apply(stage);
338 StageInterfaceValidator().apply(stage);
341 bool Compiler::check_errors(Stage &stage)
343 stable_sort(stage.diagnostics, &diagnostic_line_order);
344 return !any_of(stage.diagnostics.begin(), stage.diagnostics.end(),
345 [](const Diagnostic &d){ return d.severity==Diagnostic::ERR; });
348 bool Compiler::diagnostic_line_order(const Diagnostic &diag1, const Diagnostic &diag2)
350 if(diag1.provoking_source!=diag2.provoking_source)
352 // Sort builtins first and imported modules according to import order.
353 if(diag1.provoking_source<=BUILTIN_SOURCE)
354 return diag1.provoking_source<diag2.provoking_source;
355 else if(diag2.provoking_source<=BUILTIN_SOURCE)
358 return diag1.provoking_source>diag2.provoking_source;
360 return diag1.provoking_line<diag2.provoking_line;
363 Compiler::OptimizeResult Compiler::optimize(Stage &stage)
365 if(ConstantFolder().apply(stage))
366 resolve(stage, RESOLVE_EXPRESSIONS);
367 if(ConstantConditionEliminator().apply(stage))
368 resolve(stage, RESOLVE_VARIABLES);
370 bool any_inlined = false;
371 if(FunctionInliner().apply(stage))
373 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
376 if(AggregateDismantler().apply(stage))
378 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
381 if(ExpressionInliner().apply(stage))
383 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
387 /* Removing variables or functions may cause things from the previous stage
389 bool any_removed = UnreachableCodeRemover().apply(stage);
390 any_removed |= UnusedVariableRemover().apply(stage);
391 any_removed |= UnusedFunctionRemover().apply(stage);
392 any_removed |= UnusedTypeRemover().apply(stage);
394 return any_removed ? REDO_PREVIOUS : any_inlined ? REDO_STAGE : NEXT_STAGE;
397 void Compiler::finalize(Stage &stage, Mode mode)
399 QualifierConverter().apply(stage, features);
400 PrecisionConverter().apply(stage);
402 StructOrganizer().apply(stage);
404 // Collect bindings from all stages into the shared stage's maps
405 module->shared.texture_bindings.insert(stage.texture_bindings.begin(), stage.texture_bindings.end());
406 module->shared.uniform_block_bindings.insert(stage.uniform_block_bindings.begin(), stage.uniform_block_bindings.end());
409 void Compiler::inject_block(Block &target, const Block &source)
411 auto insert_point = target.body.begin();
412 for(const RefPtr<Statement> &s: source.body)
413 target.body.insert(insert_point, s->clone());