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);
98 for(Stage &s: module->stages)
99 DepthRangeConverter().apply(s, features);
101 for(auto i=module->stages.begin(); i!=module->stages.end(); )
103 OptimizeResult result = optimize(*i);
104 if(result==REDO_PREVIOUS)
105 i = module->stages.begin();
106 else if(result!=REDO_STAGE)
110 Stage *prev_stage = 0;
111 for(auto i=module->stages.begin(); i!=module->stages.end(); )
113 if(i->functions.empty())
114 i = module->stages.erase(i);
117 i->previous = prev_stage;
123 for(Stage &s: module->stages)
125 StructuralFeatureConverter().apply(s, features);
126 resolve(s, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS);
128 LocationAllocator().apply(*module, features);
129 for(Stage &s: module->stages)
135 string Compiler::get_combined_glsl() const
138 throw invalid_operation("Compiler::get_combined_glsl");
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)
147 glsl += format("#pragma MSP stage(%s)\n", Stage::get_stage_name(s.type));
148 glsl += Formatter().apply(s);
155 vector<Stage::Type> Compiler::get_stages() const
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);
164 string Compiler::get_stage_glsl(Stage::Type stage_type) const
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));
174 vector<uint32_t> Compiler::get_combined_spirv() const
177 throw invalid_operation("Compiler::get_combined_spirv");
179 gen.apply(*module, features);
180 return gen.get_code();
183 const map<string, unsigned> &Compiler::get_vertex_attributes() const
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())
190 throw invalid_operation("Compiler::get_vertex_attributes");
193 const map<string, unsigned> &Compiler::get_fragment_outputs() const
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())
200 throw invalid_operation("Compiler::get_fragment_outputs");
203 const map<string, unsigned> &Compiler::get_texture_bindings() const
206 throw invalid_operation("Compiler::get_texture_bindings");
207 return module->shared.texture_bindings;
210 const map<string, unsigned> &Compiler::get_uniform_block_bindings() const
213 throw invalid_operation("Compiler::get_uniform_block_bindings");
214 return module->shared.uniform_block_bindings;
217 unsigned Compiler::get_n_clip_distances() const
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);
225 const SourceMap &Compiler::get_source_map() const
227 return module->source_map;
230 string Compiler::get_stage_debug(Stage::Type stage_type, bool use_colors) const
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));
238 string Compiler::get_diagnostics() const
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));
248 void Compiler::append_module(const Module &mod, ModuleCache &mod_cache)
250 module->source_map.merge_from(mod.source_map);
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);
259 append_stage(mod.shared);
260 for(const Stage &s: mod.stages)
264 void Compiler::append_stage(const Stage &stage)
267 if(stage.type==Stage::SHARED)
268 target = &module->shared;
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)
274 auto j = module->stages.insert(i, stage.type);
275 if(i!=module->stages.end())
278 if(i!=module->stages.begin())
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);
292 void Compiler::import(ModuleCache &mod_cache, const string &name)
294 if(find(imported_names, name)!=imported_names.end())
296 imported_names.push_back(name);
298 append_module(mod_cache.get_module(name), mod_cache);
301 void Compiler::generate(Stage &stage)
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;
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);
313 // Initial resolving pass
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);
321 ArraySizer().apply(stage);
322 resolve(stage, RESOLVE_EXPRESSIONS);
326 bool Compiler::resolve(Stage &stage, unsigned &flags, unsigned bit)
332 return T().apply(stage);
335 void Compiler::resolve(Stage &stage, unsigned flags)
339 if(resolve<BlockHierarchyResolver>(stage, flags, RESOLVE_BLOCKS))
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;
352 void Compiler::validate(Stage &stage)
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);
362 bool Compiler::check_errors(Stage &stage)
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; });
369 bool Compiler::diagnostic_line_order(const Diagnostic &diag1, const Diagnostic &diag2)
371 if(diag1.provoking_source!=diag2.provoking_source)
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)
379 return diag1.provoking_source>diag2.provoking_source;
381 return diag1.provoking_line<diag2.provoking_line;
384 Compiler::OptimizeResult Compiler::optimize(Stage &stage)
386 if(ConstantFolder().apply(stage))
387 resolve(stage, RESOLVE_EXPRESSIONS);
388 if(ConstantConditionEliminator().apply(stage))
389 resolve(stage, RESOLVE_VARIABLES);
391 bool any_inlined = false;
392 if(FunctionInliner().apply(stage))
394 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
397 if(AggregateDismantler().apply(stage))
399 resolve(stage, RESOLVE_TYPES|RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
402 if(ExpressionInliner().apply(stage))
404 resolve(stage, RESOLVE_VARIABLES|RESOLVE_FUNCTIONS|RESOLVE_EXPRESSIONS);
408 /* Removing variables or functions may cause things from the previous stage
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);
415 return any_removed ? REDO_PREVIOUS : any_inlined ? REDO_STAGE : NEXT_STAGE;
418 void Compiler::finalize(Stage &stage, Mode mode)
420 QualifierConverter().apply(stage, features);
421 PrecisionConverter().apply(stage);
423 StructOrganizer().apply(stage);
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());
430 void Compiler::inject_block(Block &target, const Block &source)
432 auto insert_point = target.body.begin();
433 for(const RefPtr<Statement> &s: source.body)
434 target.body.insert(insert_point, s->clone());