blob: ad3dfc5ec812d7006d4eb92d4904aba9af39ca02 [file] [log] [blame]
alokp@chromium.org07620a52010-09-23 17:53:56 +00001//
Jamie Madill88f6e942014-02-19 10:27:53 -05002// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
alokp@chromium.org07620a52010-09-23 17:53:56 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
Jamie Madilld4a3a312014-06-25 16:04:56 -04007#include "compiler/translator/Compiler.h"
Corentin Wallez71d147f2015-02-11 11:15:24 -08008#include "compiler/translator/CallDAG.h"
Geoff Lang17732822013-08-29 13:46:49 -04009#include "compiler/translator/ForLoopUnroll.h"
10#include "compiler/translator/Initialize.h"
Geoff Lang17732822013-08-29 13:46:49 -040011#include "compiler/translator/InitializeParseContext.h"
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080012#include "compiler/translator/InitializeVariables.h"
Jamie Madill6b9cb252013-10-17 10:45:47 -040013#include "compiler/translator/ParseContext.h"
Zhenyao Moe740add2014-07-18 17:01:01 -070014#include "compiler/translator/RegenerateStructNames.h"
Geoff Lang17732822013-08-29 13:46:49 -040015#include "compiler/translator/RenameFunction.h"
Zhenyao Mocd68fe72014-07-11 10:45:44 -070016#include "compiler/translator/ScalarizeVecAndMatConstructorArgs.h"
Zhenyao Mo7cab38b2013-10-15 12:59:30 -070017#include "compiler/translator/UnfoldShortCircuitAST.h"
Geoff Lang17732822013-08-29 13:46:49 -040018#include "compiler/translator/ValidateLimitations.h"
19#include "compiler/translator/ValidateOutputs.h"
20#include "compiler/translator/VariablePacker.h"
21#include "compiler/translator/depgraph/DependencyGraph.h"
22#include "compiler/translator/depgraph/DependencyGraphOutput.h"
23#include "compiler/translator/timing/RestrictFragmentShaderTiming.h"
24#include "compiler/translator/timing/RestrictVertexShaderTiming.h"
shannon.woods@transgaming.comda1ed362013-01-25 21:54:57 +000025#include "third_party/compiler/ArrayBoundsClamper.h"
Jamie Madill183bde52014-07-02 15:31:19 -040026#include "angle_gl.h"
Jamie Madillaa72d782014-07-02 15:31:19 -040027#include "common/utilities.h"
alokp@chromium.org07620a52010-09-23 17:53:56 +000028
Jamie Madill5508f392014-02-20 13:31:36 -050029bool IsWebGLBasedSpec(ShShaderSpec spec)
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000030{
Zhenyao Modb9b40b2014-10-29 15:00:04 -070031 return (spec == SH_WEBGL_SPEC ||
32 spec == SH_CSS_SHADERS_SPEC ||
33 spec == SH_WEBGL2_SPEC);
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +000034}
35
Zhenyao Mo7faf1a12014-04-25 18:03:56 -070036size_t GetGlobalMaxTokenSize(ShShaderSpec spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050037{
Jamie Madill88f6e942014-02-19 10:27:53 -050038 // WebGL defines a max token legnth of 256, while ES2 leaves max token
39 // size undefined. ES3 defines a max size of 1024 characters.
Zhenyao Modb9b40b2014-10-29 15:00:04 -070040 switch (spec)
Jamie Madill88f6e942014-02-19 10:27:53 -050041 {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070042 case SH_WEBGL_SPEC:
43 case SH_CSS_SHADERS_SPEC:
Jamie Madill88f6e942014-02-19 10:27:53 -050044 return 256;
Zhenyao Modb9b40b2014-10-29 15:00:04 -070045 default:
Jamie Madill88f6e942014-02-19 10:27:53 -050046 return 1024;
47 }
48}
49
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000050namespace {
Zhenyao Modb9b40b2014-10-29 15:00:04 -070051
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080052class TScopedPoolAllocator
53{
54 public:
55 TScopedPoolAllocator(TPoolAllocator* allocator) : mAllocator(allocator)
56 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040057 mAllocator->push();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000058 SetGlobalPoolAllocator(mAllocator);
59 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080060 ~TScopedPoolAllocator()
61 {
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000062 SetGlobalPoolAllocator(NULL);
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040063 mAllocator->pop();
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000064 }
65
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080066 private:
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000067 TPoolAllocator* mAllocator;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040068};
69
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080070class TScopedSymbolTableLevel
71{
72 public:
73 TScopedSymbolTableLevel(TSymbolTable* table) : mTable(table)
74 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040075 ASSERT(mTable->atBuiltInLevel());
76 mTable->push();
77 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080078 ~TScopedSymbolTableLevel()
79 {
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040080 while (!mTable->atBuiltInLevel())
81 mTable->pop();
82 }
83
Zhenyao Mo4a667fe2014-02-11 12:35:01 -080084 private:
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -040085 TSymbolTable* mTable;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +000086};
Zhenyao Modb9b40b2014-10-29 15:00:04 -070087
88int MapSpecToShaderVersion(ShShaderSpec spec)
89{
90 switch (spec)
91 {
92 case SH_GLES2_SPEC:
93 case SH_WEBGL_SPEC:
94 case SH_CSS_SHADERS_SPEC:
95 return 100;
96 case SH_GLES3_SPEC:
97 case SH_WEBGL2_SPEC:
98 return 300;
99 default:
100 UNREACHABLE();
101 return 0;
102 }
103}
104
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000105} // namespace
106
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800107TShHandleBase::TShHandleBase()
108{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000109 allocator.push();
110 SetGlobalPoolAllocator(&allocator);
111}
112
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800113TShHandleBase::~TShHandleBase()
114{
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000115 SetGlobalPoolAllocator(NULL);
116 allocator.popAll();
117}
118
Jamie Madill183bde52014-07-02 15:31:19 -0400119TCompiler::TCompiler(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000120 : shaderType(type),
zmo@google.comf420c422011-09-12 18:27:59 +0000121 shaderSpec(spec),
Jamie Madill68fe74a2014-05-27 12:56:01 -0400122 outputType(output),
Jamie Madilleb1a0102013-07-08 13:31:38 -0400123 maxUniformVectors(0),
124 maxExpressionComplexity(0),
125 maxCallStackDepth(0),
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000126 fragmentPrecisionHigh(false),
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000127 clampingStrategy(SH_CLAMP_WITH_CLAMP_INTRINSIC),
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200128 builtInFunctionEmulator(),
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200129 mSourcePath(NULL)
alokp@chromium.org4888ceb2010-10-01 21:13:12 +0000130{
131}
132
133TCompiler::~TCompiler()
134{
135}
136
137bool TCompiler::Init(const ShBuiltInResources& resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000138{
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000139 shaderVersion = 100;
Jamie Madill183bde52014-07-02 15:31:19 -0400140 maxUniformVectors = (shaderType == GL_VERTEX_SHADER) ?
gman@chromium.org8d804792012-10-17 21:33:48 +0000141 resources.MaxVertexUniformVectors :
142 resources.MaxFragmentUniformVectors;
Jamie Madilleb1a0102013-07-08 13:31:38 -0400143 maxExpressionComplexity = resources.MaxExpressionComplexity;
144 maxCallStackDepth = resources.MaxCallStackDepth;
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400145
146 SetGlobalPoolAllocator(&allocator);
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000147
alokp@chromium.org07620a52010-09-23 17:53:56 +0000148 // Generate built-in symbol table.
149 if (!InitBuiltInSymbolTable(resources))
150 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000151 InitExtensionBehavior(resources, extensionBehavior);
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000152 fragmentPrecisionHigh = resources.FragmentPrecisionHigh == 1;
alokp@chromium.orgbafcbaa2010-11-23 19:07:43 +0000153
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000154 arrayBoundsClamper.SetClampingStrategy(resources.ArrayIndexClampingStrategy);
155 clampingStrategy = resources.ArrayIndexClampingStrategy;
156
daniel@transgaming.comc23f4612012-11-28 19:42:57 +0000157 hashFunction = resources.HashFunction;
158
alokp@chromium.org07620a52010-09-23 17:53:56 +0000159 return true;
160}
161
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200162TIntermNode *TCompiler::compileTreeForTesting(const char* const shaderStrings[],
163 size_t numStrings, int compileOptions)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000164{
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200165 return compileTreeImpl(shaderStrings, numStrings, compileOptions);
166}
167
168TIntermNode *TCompiler::compileTreeImpl(const char* const shaderStrings[],
169 size_t numStrings, int compileOptions)
170{
alokp@chromium.org07620a52010-09-23 17:53:56 +0000171 clearResults();
172
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200173 ASSERT(numStrings > 0);
174 ASSERT(GetGlobalPoolAllocator());
alokp@chromium.org07620a52010-09-23 17:53:56 +0000175
David Yen0fbd1282015-02-02 14:46:09 -0800176 // Reset the extension behavior for each compilation unit.
177 ResetExtensionBehavior(extensionBehavior);
178
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000179 // If compiling for WebGL, validate loop and indexing as well.
Jamie Madill5508f392014-02-20 13:31:36 -0500180 if (IsWebGLBasedSpec(shaderSpec))
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000181 compileOptions |= SH_VALIDATE_LOOP_INDEXING;
alokp@chromium.org1f299542010-11-12 15:50:23 +0000182
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000183 // First string is path of source file if flag is set. The actual source follows.
shannon.woods@transgaming.comd64b3da2013-02-28 23:19:26 +0000184 size_t firstSource = 0;
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000185 if (compileOptions & SH_SOURCE_PATH)
186 {
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200187 mSourcePath = shaderStrings[0];
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000188 ++firstSource;
189 }
190
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200191 bool debugShaderPrecision = getResources().WEBGL_debug_shader_precision == 1;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000192 TIntermediate intermediate(infoSink);
193 TParseContext parseContext(symbolTable, extensionBehavior, intermediate,
zmo@google.comdc4b4f82011-06-17 00:42:53 +0000194 shaderType, shaderSpec, compileOptions, true,
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200195 infoSink, debugShaderPrecision);
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200196
shannon.woods%transgaming.com@gtempaccount.comcbb6b6a2013-04-13 03:27:47 +0000197 parseContext.fragmentPrecisionHigh = fragmentPrecisionHigh;
Alok Priyadarshi8156b6b2013-09-23 14:56:58 -0400198 SetGlobalParseContext(&parseContext);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000199
200 // We preserve symbols at the built-in level from compile-to-compile.
201 // Start pushing the user-defined symbols at global level.
Alok Priyadarshibc3f1ac2013-09-23 14:57:02 -0400202 TScopedSymbolTableLevel scopedSymbolLevel(&symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000203
204 // Parse shader.
205 bool success =
apatrick@chromium.org0f4cefe2011-01-26 19:30:57 +0000206 (PaParseStrings(numStrings - firstSource, &shaderStrings[firstSource], NULL, &parseContext) == 0) &&
alokp@chromium.org07620a52010-09-23 17:53:56 +0000207 (parseContext.treeRoot != NULL);
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000208
shannon.woods%transgaming.com@gtempaccount.com5524db02013-04-13 03:38:16 +0000209 shaderVersion = parseContext.getShaderVersion();
Zhenyao Modb9b40b2014-10-29 15:00:04 -0700210 if (success && MapSpecToShaderVersion(shaderSpec) < shaderVersion)
211 {
212 infoSink.info.prefix(EPrefixError);
213 infoSink.info << "unsupported shader version";
214 success = false;
215 }
shannon.woods%transgaming.com@gtempaccount.com0bbed382013-04-13 03:38:07 +0000216
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200217 TIntermNode *root = NULL;
218
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800219 if (success)
220 {
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700221 mPragma = parseContext.pragma();
222 if (mPragma.stdgl.invariantAll)
223 {
224 symbolTable.setGlobalInvariant();
225 }
226
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200227 root = parseContext.treeRoot;
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000228 success = intermediate.postProcess(root);
229
Jamie Madill6654bc92014-03-26 14:01:57 -0400230 // Disallow expressions deemed too complex.
231 if (success && (compileOptions & SH_LIMIT_EXPRESSION_COMPLEXITY))
232 success = limitExpressionComplexity(root);
233
Corentin Wallez71d147f2015-02-11 11:15:24 -0800234 // Create the function DAG and check there is no recursion
zmo@google.comb1762df2011-07-30 02:04:23 +0000235 if (success)
Corentin Wallez71d147f2015-02-11 11:15:24 -0800236 success = initCallDag(root);
237
238 if (success && (compileOptions & SH_LIMIT_CALL_STACK_DEPTH))
239 success = checkCallDepth();
240
241 // Checks which functions are used and if "main" exists
242 if (success)
243 {
244 functionMetadata.clear();
245 functionMetadata.resize(mCallDag.size());
246 success = tagUsedFunctions();
247 }
zmo@google.comb1762df2011-07-30 02:04:23 +0000248
Corentin Walleza094a8a2015-04-07 11:53:06 -0700249 if (success && !(compileOptions & SH_DONT_PRUNE_UNUSED_FUNCTIONS))
250 success = pruneUnusedFunctions(root);
251
Jamie Madill183bde52014-07-02 15:31:19 -0400252 if (success && shaderVersion == 300 && shaderType == GL_FRAGMENT_SHADER)
Jamie Madill05a80ce2013-06-20 11:55:49 -0400253 success = validateOutputs(root);
254
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000255 if (success && (compileOptions & SH_VALIDATE_LOOP_INDEXING))
256 success = validateLimitations(root);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000257
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000258 if (success && (compileOptions & SH_TIMING_RESTRICTIONS))
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000259 success = enforceTimingRestrictions(root, (compileOptions & SH_DEPENDENCY_GRAPH) != 0);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000260
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +0000261 if (success && shaderSpec == SH_CSS_SHADERS_SPEC)
262 rewriteCSSShader(root);
263
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000264 // Unroll for-loop markup needs to happen after validateLimitations pass.
265 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_INTEGER_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800266 {
267 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kIntegerIndex);
Zhenyao Mo550c6002014-02-26 15:40:48 -0800268 root->traverse(&marker);
269 }
270 if (success && (compileOptions & SH_UNROLL_FOR_LOOP_WITH_SAMPLER_ARRAY_INDEX))
Zhenyao Mo3cdfcce2014-03-07 13:00:08 -0800271 {
272 ForLoopUnrollMarker marker(ForLoopUnrollMarker::kSamplerArrayIndex);
Zhenyao Mo550c6002014-02-26 15:40:48 -0800273 root->traverse(&marker);
274 if (marker.samplerArrayIndexIsFloatLoopIndex())
275 {
276 infoSink.info.prefix(EPrefixError);
277 infoSink.info << "sampler array index is float loop index";
278 success = false;
279 }
280 }
zmo@google.com0c6bb7a2011-08-17 19:39:58 +0000281
zmo@google.com32e97312011-08-24 01:03:11 +0000282 // Built-in function emulation needs to happen after validateLimitations pass.
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200283 if (success)
284 {
285 initBuiltInFunctionEmulator(&builtInFunctionEmulator, compileOptions);
zmo@google.com32e97312011-08-24 01:03:11 +0000286 builtInFunctionEmulator.MarkBuiltInFunctionsForEmulation(root);
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200287 }
zmo@google.com32e97312011-08-24 01:03:11 +0000288
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000289 // Clamping uniform array bounds needs to happen after validateLimitations pass.
290 if (success && (compileOptions & SH_CLAMP_INDIRECT_ARRAY_BOUNDS))
291 arrayBoundsClamper.MarkIndirectArrayBoundsForClamping(root);
292
Jamie Madill183bde52014-07-02 15:31:19 -0400293 if (success && shaderType == GL_VERTEX_SHADER && (compileOptions & SH_INIT_GL_POSITION))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800294 initializeGLPosition(root);
Zhenyao Moac44cd22013-09-23 14:57:09 -0400295
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800296 if (success && (compileOptions & SH_UNFOLD_SHORT_CIRCUIT))
297 {
Zhenyao Mo7cab38b2013-10-15 12:59:30 -0700298 UnfoldShortCircuitAST unfoldShortCircuit;
299 root->traverse(&unfoldShortCircuit);
300 unfoldShortCircuit.updateTree();
301 }
302
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800303 if (success && (compileOptions & SH_VARIABLES))
304 {
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400305 collectVariables(root);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800306 if (compileOptions & SH_ENFORCE_PACKING_RESTRICTIONS)
307 {
gman@chromium.org8d804792012-10-17 21:33:48 +0000308 success = enforcePackingRestrictions();
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800309 if (!success)
310 {
Jamie Madill075edd82013-07-08 13:30:19 -0400311 infoSink.info.prefix(EPrefixError);
312 infoSink.info << "too many uniforms";
gman@chromium.org8d804792012-10-17 21:33:48 +0000313 }
314 }
Jamie Madill183bde52014-07-02 15:31:19 -0400315 if (success && shaderType == GL_VERTEX_SHADER &&
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800316 (compileOptions & SH_INIT_VARYINGS_WITHOUT_STATIC_USE))
317 initializeVaryingsWithoutStaticUse(root);
gman@chromium.org8d804792012-10-17 21:33:48 +0000318 }
zmo@google.comfd747b82011-04-23 01:30:07 +0000319
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700320 if (success && (compileOptions & SH_SCALARIZE_VEC_AND_MAT_CONSTRUCTOR_ARGS))
321 {
Zhenyao Modaf56572014-08-06 16:18:30 -0700322 ScalarizeVecAndMatConstructorArgs scalarizer(
323 shaderType, fragmentPrecisionHigh);
Zhenyao Mocd68fe72014-07-11 10:45:44 -0700324 root->traverse(&scalarizer);
325 }
326
Zhenyao Moe740add2014-07-18 17:01:01 -0700327 if (success && (compileOptions & SH_REGENERATE_STRUCT_NAMES))
328 {
329 RegenerateStructNames gen(symbolTable, shaderVersion);
330 root->traverse(&gen);
331 }
alokp@chromium.org07620a52010-09-23 17:53:56 +0000332 }
333
Zhenyao Mo7faf1a12014-04-25 18:03:56 -0700334 SetGlobalParseContext(NULL);
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200335 if (success)
336 return root;
337
338 return NULL;
339}
340
341bool TCompiler::compile(const char* const shaderStrings[],
342 size_t numStrings, int compileOptions)
343{
344 if (numStrings == 0)
345 return true;
346
347 TScopedPoolAllocator scopedAlloc(&allocator);
348 TIntermNode *root = compileTreeImpl(shaderStrings, numStrings, compileOptions);
349
350 if (root)
351 {
352 if (compileOptions & SH_INTERMEDIATE_TREE)
353 TIntermediate::outputTree(root, infoSink.info);
354
355 if (compileOptions & SH_OBJECT_CODE)
356 translate(root, compileOptions);
357
358 // The IntermNode tree doesn't need to be deleted here, since the
359 // memory will be freed in a big chunk by the PoolAllocator.
360 return true;
361 }
362 return false;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000363}
364
Nicolas Capens49a88872013-06-20 09:54:03 -0400365bool TCompiler::InitBuiltInSymbolTable(const ShBuiltInResources &resources)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000366{
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000367 compileResources = resources;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400368 setResourceString();
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000369
Nicolas Capens49a88872013-06-20 09:54:03 -0400370 assert(symbolTable.isEmpty());
371 symbolTable.push(); // COMMON_BUILTINS
372 symbolTable.push(); // ESSL1_BUILTINS
373 symbolTable.push(); // ESSL3_BUILTINS
shannonwoods@chromium.org2ac0be92013-05-30 00:02:27 +0000374
Nicolas Capens49a88872013-06-20 09:54:03 -0400375 TPublicType integer;
376 integer.type = EbtInt;
377 integer.primarySize = 1;
378 integer.secondarySize = 1;
379 integer.array = false;
380
381 TPublicType floatingPoint;
382 floatingPoint.type = EbtFloat;
383 floatingPoint.primarySize = 1;
384 floatingPoint.secondarySize = 1;
385 floatingPoint.array = false;
386
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400387 TPublicType sampler;
388 sampler.primarySize = 1;
389 sampler.secondarySize = 1;
390 sampler.array = false;
391
Nicolas Capens49a88872013-06-20 09:54:03 -0400392 switch(shaderType)
393 {
Jamie Madill183bde52014-07-02 15:31:19 -0400394 case GL_FRAGMENT_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400395 symbolTable.setDefaultPrecision(integer, EbpMedium);
396 break;
Jamie Madill183bde52014-07-02 15:31:19 -0400397 case GL_VERTEX_SHADER:
Nicolas Capens49a88872013-06-20 09:54:03 -0400398 symbolTable.setDefaultPrecision(integer, EbpHigh);
399 symbolTable.setDefaultPrecision(floatingPoint, EbpHigh);
400 break;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800401 default:
402 assert(false && "Language not supported");
Nicolas Capens49a88872013-06-20 09:54:03 -0400403 }
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400404 // We set defaults for all the sampler types, even those that are
405 // only available if an extension exists.
406 for (int samplerType = EbtGuardSamplerBegin + 1;
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800407 samplerType < EbtGuardSamplerEnd; ++samplerType)
408 {
Zhenyao Moa5a1dfc2013-09-23 14:57:03 -0400409 sampler.type = static_cast<TBasicType>(samplerType);
410 symbolTable.setDefaultPrecision(sampler, EbpLow);
411 }
Nicolas Capens49a88872013-06-20 09:54:03 -0400412
Jamie Madill1b452142013-07-12 14:51:11 -0400413 InsertBuiltInFunctions(shaderType, shaderSpec, resources, symbolTable);
Nicolas Capens49a88872013-06-20 09:54:03 -0400414
415 IdentifyBuiltIns(shaderType, shaderSpec, resources, symbolTable);
416
417 return true;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000418}
419
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400420void TCompiler::setResourceString()
421{
422 std::ostringstream strstream;
423 strstream << ":MaxVertexAttribs:" << compileResources.MaxVertexAttribs
424 << ":MaxVertexUniformVectors:" << compileResources.MaxVertexUniformVectors
425 << ":MaxVaryingVectors:" << compileResources.MaxVaryingVectors
426 << ":MaxVertexTextureImageUnits:" << compileResources.MaxVertexTextureImageUnits
427 << ":MaxCombinedTextureImageUnits:" << compileResources.MaxCombinedTextureImageUnits
428 << ":MaxTextureImageUnits:" << compileResources.MaxTextureImageUnits
429 << ":MaxFragmentUniformVectors:" << compileResources.MaxFragmentUniformVectors
430 << ":MaxDrawBuffers:" << compileResources.MaxDrawBuffers
431 << ":OES_standard_derivatives:" << compileResources.OES_standard_derivatives
432 << ":OES_EGL_image_external:" << compileResources.OES_EGL_image_external
433 << ":ARB_texture_rectangle:" << compileResources.ARB_texture_rectangle
434 << ":EXT_draw_buffers:" << compileResources.EXT_draw_buffers
435 << ":FragmentPrecisionHigh:" << compileResources.FragmentPrecisionHigh
436 << ":MaxExpressionComplexity:" << compileResources.MaxExpressionComplexity
437 << ":MaxCallStackDepth:" << compileResources.MaxCallStackDepth
438 << ":EXT_frag_depth:" << compileResources.EXT_frag_depth
439 << ":EXT_shader_texture_lod:" << compileResources.EXT_shader_texture_lod
Erik Dahlströmea7a2122014-11-17 16:15:57 +0100440 << ":EXT_shader_framebuffer_fetch:" << compileResources.EXT_shader_framebuffer_fetch
441 << ":NV_shader_framebuffer_fetch:" << compileResources.NV_shader_framebuffer_fetch
442 << ":ARM_shader_framebuffer_fetch:" << compileResources.ARM_shader_framebuffer_fetch
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400443 << ":MaxVertexOutputVectors:" << compileResources.MaxVertexOutputVectors
444 << ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
445 << ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
Olli Etuahoe61209a2014-09-26 12:01:17 +0300446 << ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200447 << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
448 << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision;
Shannon Woods2d76e5f2014-05-16 17:46:41 -0400449
450 builtInResourcesString = strstream.str();
451}
452
alokp@chromium.org07620a52010-09-23 17:53:56 +0000453void TCompiler::clearResults()
454{
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000455 arrayBoundsClamper.Cleanup();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000456 infoSink.info.erase();
457 infoSink.obj.erase();
458 infoSink.debug.erase();
459
Jamie Madilled27c722014-07-02 15:31:23 -0400460 attributes.clear();
461 outputVariables.clear();
alokp@chromium.org07620a52010-09-23 17:53:56 +0000462 uniforms.clear();
Jamie Madill23a8a432014-07-09 13:27:42 -0400463 expandedUniforms.clear();
Zhenyao Mod2d340b2013-09-23 14:57:05 -0400464 varyings.clear();
Jamie Madilled27c722014-07-02 15:31:23 -0400465 interfaceBlocks.clear();
zmo@google.coma3b4ab42011-09-16 00:53:26 +0000466
467 builtInFunctionEmulator.Cleanup();
daniel@transgaming.com0aa3b5a2012-11-28 19:43:24 +0000468
469 nameMap.clear();
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200470
471 mSourcePath = NULL;
alokp@chromium.org07620a52010-09-23 17:53:56 +0000472}
473
Corentin Wallez71d147f2015-02-11 11:15:24 -0800474bool TCompiler::initCallDag(TIntermNode *root)
zmo@google.comb1762df2011-07-30 02:04:23 +0000475{
Corentin Wallez71d147f2015-02-11 11:15:24 -0800476 mCallDag.clear();
477
478 switch (mCallDag.init(root, &infoSink.info))
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800479 {
Corentin Wallez71d147f2015-02-11 11:15:24 -0800480 case CallDAG::INITDAG_SUCCESS:
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800481 return true;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800482 case CallDAG::INITDAG_RECURSION:
483 infoSink.info.prefix(EPrefixError);
484 infoSink.info << "Function recursion detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800485 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800486 case CallDAG::INITDAG_UNDEFINED:
487 infoSink.info.prefix(EPrefixError);
488 infoSink.info << "Unimplemented function detected";
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800489 return false;
Corentin Wallez71d147f2015-02-11 11:15:24 -0800490 }
491
492 UNREACHABLE();
493 return true;
494}
495
496bool TCompiler::checkCallDepth()
497{
498 std::vector<int> depths(mCallDag.size());
499
500 for (size_t i = 0; i < mCallDag.size(); i++)
501 {
502 int depth = 0;
503 auto &record = mCallDag.getRecordFromIndex(i);
504
505 for (auto &calleeIndex : record.callees)
506 {
507 depth = std::max(depth, depths[calleeIndex] + 1);
508 }
509
510 depths[i] = depth;
511
512 if (depth >= maxCallStackDepth)
513 {
514 // Trace back the function chain to have a meaningful info log.
515 infoSink.info.prefix(EPrefixError);
516 infoSink.info << "Call stack too deep (larger than " << maxCallStackDepth
517 << ") with the following call chain: " << record.name;
518
519 int currentFunction = i;
520 int currentDepth = depth;
521
522 while (currentFunction != -1)
523 {
524 infoSink.info << " -> " << mCallDag.getRecordFromIndex(currentFunction).name;
525
526 int nextFunction = -1;
527 for (auto& calleeIndex : mCallDag.getRecordFromIndex(currentFunction).callees)
528 {
529 if (depths[calleeIndex] == currentDepth - 1)
530 {
531 currentDepth--;
532 nextFunction = calleeIndex;
533 }
534 }
535
536 currentFunction = nextFunction;
537 }
538
539 return false;
540 }
541 }
542
543 return true;
544}
545
546bool TCompiler::tagUsedFunctions()
547{
548 // Search from main, starting from the end of the DAG as it usually is the root.
549 for (int i = mCallDag.size(); i-- > 0;)
550 {
551 if (mCallDag.getRecordFromIndex(i).name == "main(")
552 {
553 internalTagUsedFunction(i);
554 return true;
555 }
556 }
557
558 infoSink.info.prefix(EPrefixError);
559 infoSink.info << "Missing main()";
560 return false;
561}
562
563void TCompiler::internalTagUsedFunction(size_t index)
564{
565 if (functionMetadata[index].used)
566 {
567 return;
568 }
569
570 functionMetadata[index].used = true;
571
572 for (int calleeIndex : mCallDag.getRecordFromIndex(index).callees)
573 {
574 internalTagUsedFunction(calleeIndex);
zmo@google.comb1762df2011-07-30 02:04:23 +0000575 }
576}
577
Corentin Walleza094a8a2015-04-07 11:53:06 -0700578// A predicate for the stl that returns if a top-level node is unused
579class TCompiler::UnusedPredicate
580{
581 public:
582 UnusedPredicate(const CallDAG *callDag, const std::vector<FunctionMetadata> *metadatas)
583 : mCallDag(callDag),
584 mMetadatas(metadatas)
585 {
586 }
587
588 bool operator ()(TIntermNode *node)
589 {
590 const TIntermAggregate *asAggregate = node->getAsAggregate();
591
592 if (asAggregate == nullptr)
593 {
594 return false;
595 }
596
597 if (!(asAggregate->getOp() == EOpFunction || asAggregate->getOp() == EOpPrototype))
598 {
599 return false;
600 }
601
602 size_t callDagIndex = mCallDag->findIndex(asAggregate);
603 if (callDagIndex == CallDAG::InvalidIndex)
604 {
605 // This happens only for unimplemented prototypes which are thus unused
606 ASSERT(asAggregate->getOp() == EOpPrototype);
607 return true;
608 }
609
610 ASSERT(callDagIndex < mMetadatas->size());
611 return !(*mMetadatas)[callDagIndex].used;
612 }
613
614 private:
615 const CallDAG *mCallDag;
616 const std::vector<FunctionMetadata> *mMetadatas;
617};
618
619bool TCompiler::pruneUnusedFunctions(TIntermNode *root)
620{
621 TIntermAggregate *rootNode = root->getAsAggregate();
622 ASSERT(rootNode != nullptr);
623
624 UnusedPredicate isUnused(&mCallDag, &functionMetadata);
625 TIntermSequence *sequence = rootNode->getSequence();
626 sequence->erase(std::remove_if(sequence->begin(), sequence->end(), isUnused), sequence->end());
627
628 return true;
629}
630
Jamie Madill05a80ce2013-06-20 11:55:49 -0400631bool TCompiler::validateOutputs(TIntermNode* root)
632{
633 ValidateOutputs validateOutputs(infoSink.info, compileResources.MaxDrawBuffers);
634 root->traverse(&validateOutputs);
635 return (validateOutputs.numErrors() == 0);
636}
637
maxvujovic@gmail.com430f5e02012-06-08 17:47:59 +0000638void TCompiler::rewriteCSSShader(TIntermNode* root)
639{
640 RenameFunction renamer("main(", "css_main(");
641 root->traverse(&renamer);
642}
643
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800644bool TCompiler::validateLimitations(TIntermNode* root)
645{
alokp@chromium.orgb59a7782010-11-24 18:38:33 +0000646 ValidateLimitations validate(shaderType, infoSink.info);
647 root->traverse(&validate);
648 return validate.numErrors() == 0;
649}
650
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000651bool TCompiler::enforceTimingRestrictions(TIntermNode* root, bool outputGraph)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000652{
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800653 if (shaderSpec != SH_WEBGL_SPEC)
654 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000655 infoSink.info << "Timing restrictions must be enforced under the WebGL spec.";
656 return false;
657 }
658
Jamie Madill183bde52014-07-02 15:31:19 -0400659 if (shaderType == GL_FRAGMENT_SHADER)
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800660 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000661 TDependencyGraph graph(root);
662
663 // Output any errors first.
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000664 bool success = enforceFragmentShaderTimingRestrictions(graph);
Jamie Madill5508f392014-02-20 13:31:36 -0500665
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000666 // Then, output the dependency graph.
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800667 if (outputGraph)
668 {
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000669 TDependencyGraphOutput output(infoSink.info);
670 output.outputAllSpanningTrees(graph);
671 }
Jamie Madill5508f392014-02-20 13:31:36 -0500672
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000673 return success;
674 }
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800675 else
676 {
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000677 return enforceVertexShaderTimingRestrictions(root);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000678 }
679}
680
Jamie Madilleb1a0102013-07-08 13:31:38 -0400681bool TCompiler::limitExpressionComplexity(TIntermNode* root)
682{
Jamie Madill6654bc92014-03-26 14:01:57 -0400683 TMaxDepthTraverser traverser(maxExpressionComplexity+1);
Jamie Madilleb1a0102013-07-08 13:31:38 -0400684 root->traverse(&traverser);
Jamie Madill6654bc92014-03-26 14:01:57 -0400685
686 if (traverser.getMaxDepth() > maxExpressionComplexity)
687 {
688 infoSink.info << "Expression too complex.";
689 return false;
690 }
691
Jamie Madilleb1a0102013-07-08 13:31:38 -0400692 TDependencyGraph graph(root);
693
694 for (TFunctionCallVector::const_iterator iter = graph.beginUserDefinedFunctionCalls();
695 iter != graph.endUserDefinedFunctionCalls();
696 ++iter)
697 {
698 TGraphFunctionCall* samplerSymbol = *iter;
699 TDependencyGraphTraverser graphTraverser;
700 samplerSymbol->traverse(&graphTraverser);
701 }
702
Jamie Madilleb1a0102013-07-08 13:31:38 -0400703 return true;
704}
705
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000706bool TCompiler::enforceFragmentShaderTimingRestrictions(const TDependencyGraph& graph)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000707{
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000708 RestrictFragmentShaderTiming restrictor(infoSink.info);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000709 restrictor.enforceRestrictions(graph);
710 return restrictor.numErrors() == 0;
711}
712
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000713bool TCompiler::enforceVertexShaderTimingRestrictions(TIntermNode* root)
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000714{
maxvujovic@gmail.com77222c92012-06-04 21:06:05 +0000715 RestrictVertexShaderTiming restrictor(infoSink.info);
maxvujovic@gmail.com66ebd012012-05-30 22:18:11 +0000716 restrictor.enforceRestrictions(root);
717 return restrictor.numErrors() == 0;
718}
719
Zhenyao Mo74da9f22013-09-23 14:57:01 -0400720void TCompiler::collectVariables(TIntermNode* root)
alokp@chromium.org07620a52010-09-23 17:53:56 +0000721{
Jamie Madilla2fbb842014-09-03 09:40:47 -0400722 sh::CollectVariables collect(&attributes,
723 &outputVariables,
724 &uniforms,
725 &varyings,
726 &interfaceBlocks,
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700727 hashFunction,
728 symbolTable);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000729 root->traverse(&collect);
Jamie Madill23a8a432014-07-09 13:27:42 -0400730
Zhenyao Mo409078f2014-10-28 13:23:18 -0700731 // This is for enforcePackingRestriction().
732 sh::ExpandUniforms(uniforms, &expandedUniforms);
alokp@chromium.org07620a52010-09-23 17:53:56 +0000733}
zmo@google.comfd747b82011-04-23 01:30:07 +0000734
gman@chromium.org8d804792012-10-17 21:33:48 +0000735bool TCompiler::enforcePackingRestrictions()
736{
737 VariablePacker packer;
Jamie Madill23a8a432014-07-09 13:27:42 -0400738 return packer.CheckVariablesWithinPackingLimits(maxUniformVectors, expandedUniforms);
gman@chromium.org8d804792012-10-17 21:33:48 +0000739}
740
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800741void TCompiler::initializeGLPosition(TIntermNode* root)
742{
743 InitializeVariables::InitVariableInfoList variables;
744 InitializeVariables::InitVariableInfo var(
745 "gl_Position", TType(EbtFloat, EbpUndefined, EvqPosition, 4));
746 variables.push_back(var);
747 InitializeVariables initializer(variables);
748 root->traverse(&initializer);
749}
750
751void TCompiler::initializeVaryingsWithoutStaticUse(TIntermNode* root)
752{
753 InitializeVariables::InitVariableInfoList variables;
754 for (size_t ii = 0; ii < varyings.size(); ++ii)
755 {
Jamie Madilla718c1e2014-07-02 15:31:22 -0400756 const sh::Varying& varying = varyings[ii];
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800757 if (varying.staticUse)
758 continue;
Jamie Madillaa72d782014-07-02 15:31:19 -0400759 unsigned char primarySize = static_cast<unsigned char>(gl::VariableColumnCount(varying.type));
760 unsigned char secondarySize = static_cast<unsigned char>(gl::VariableRowCount(varying.type));
Jamie Madilla718c1e2014-07-02 15:31:22 -0400761 TType type(EbtFloat, EbpUndefined, EvqVaryingOut, primarySize, secondarySize, varying.isArray());
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800762 TString name = varying.name.c_str();
Jamie Madilla718c1e2014-07-02 15:31:22 -0400763 if (varying.isArray())
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800764 {
Jamie Madilla718c1e2014-07-02 15:31:22 -0400765 type.setArraySize(varying.arraySize);
Zhenyao Mo4a667fe2014-02-11 12:35:01 -0800766 name = name.substr(0, name.find_first_of('['));
767 }
768
769 InitializeVariables::InitVariableInfo var(name, type);
770 variables.push_back(var);
771 }
772 InitializeVariables initializer(variables);
773 root->traverse(&initializer);
774}
775
zmo@google.com5601ea02011-06-10 18:23:25 +0000776const TExtensionBehavior& TCompiler::getExtensionBehavior() const
777{
778 return extensionBehavior;
779}
zmo@google.com32e97312011-08-24 01:03:11 +0000780
Olli Etuahoa3a5cc62015-02-13 13:12:22 +0200781const char *TCompiler::getSourcePath() const
782{
783 return mSourcePath;
784}
785
shannon.woods%transgaming.com@gtempaccount.com18b4c4b2013-04-13 03:31:40 +0000786const ShBuiltInResources& TCompiler::getResources() const
787{
788 return compileResources;
789}
790
daniel@transgaming.com4167cc92013-01-11 04:11:53 +0000791const ArrayBoundsClamper& TCompiler::getArrayBoundsClamper() const
792{
793 return arrayBoundsClamper;
794}
795
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000796ShArrayIndexClampingStrategy TCompiler::getArrayIndexClampingStrategy() const
797{
798 return clampingStrategy;
799}
800
Olli Etuaho8efc5ad2015-03-03 17:21:10 +0200801const BuiltInFunctionEmulator& TCompiler::getBuiltInFunctionEmulator() const
shannon.woods@transgaming.com1d432bb2013-01-25 21:57:28 +0000802{
803 return builtInFunctionEmulator;
804}
Zhenyao Mo94ac7b72014-10-15 18:22:08 -0700805
806void TCompiler::writePragma()
807{
808 TInfoSinkBase &sink = infoSink.obj;
809 if (mPragma.stdgl.invariantAll)
810 sink << "#pragma STDGL invariant(all)\n";
811}