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