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