Add mediump and lowp precision emulation support for GLSL output
This implements the rounding as specified in WEBGL_debug_shader_precision
extension proposal for desktop GLSL and ESSL output. The bulk of the new
functionality is added in the form of a new EmulatePrecision AST
traverser, which inserts calls to the rounding routines angle_frm and
angle_frl in the appropriate places, and writes the rounding routines
themselves to the shader.
Compound assignments which are subject to emulation are transformed from
"x op= y" to "angle_compound_op_frm(x, y)", a call to a function which
does the appropriate rounding and places the result of the operation to
x.
The angle_ prefixed names should not clash with user-defined names if
name hashing is on. If name hashing is not on, the precision emulation
can only be used if the angle_ prefix is reserved for use by ANGLE.
To support the rounding routines in output, a new operator type is added
for internal helper function calls, which are not subject to name
hashing.
In ESSL output, all variables are forced to highp when precision
emulation is on to ensure consistency with how precision emulation
performs on desktop.
Comprehensive tests for the added code generation are included.
BUG=angle:787
Change-Id: I0d0ad9327888f803a32e79b64b08763c654c913b
Reviewed-on: https://chromium-review.googlesource.com/229631
Reviewed-by: Jamie Madill <jmadill@chromium.org>
Tested-by: Olli Etuaho <oetuaho@nvidia.com>
diff --git a/src/compiler/translator/Compiler.cpp b/src/compiler/translator/Compiler.cpp
index 5c62a64..ab1c9dd 100644
--- a/src/compiler/translator/Compiler.cpp
+++ b/src/compiler/translator/Compiler.cpp
@@ -182,10 +182,12 @@
++firstSource;
}
+ bool debugShaderPrecision = getResources().WEBGL_debug_shader_precision == 1;
TIntermediate intermediate(infoSink);
TParseContext parseContext(symbolTable, extensionBehavior, intermediate,
shaderType, shaderSpec, compileOptions, true,
- sourcePath, infoSink);
+ sourcePath, infoSink, debugShaderPrecision);
+
parseContext.fragmentPrecisionHigh = fragmentPrecisionHigh;
SetGlobalParseContext(&parseContext);
@@ -394,7 +396,8 @@
<< ":MaxFragmentInputVectors:" << compileResources.MaxFragmentInputVectors
<< ":MinProgramTexelOffset:" << compileResources.MinProgramTexelOffset
<< ":MaxProgramTexelOffset:" << compileResources.MaxProgramTexelOffset
- << ":NV_draw_buffers:" << compileResources.NV_draw_buffers;
+ << ":NV_draw_buffers:" << compileResources.NV_draw_buffers
+ << ":WEBGL_debug_shader_precision:" << compileResources.WEBGL_debug_shader_precision;
builtInResourcesString = strstream.str();
}
diff --git a/src/compiler/translator/DirectiveHandler.cpp b/src/compiler/translator/DirectiveHandler.cpp
index f67a03a..936c00a 100644
--- a/src/compiler/translator/DirectiveHandler.cpp
+++ b/src/compiler/translator/DirectiveHandler.cpp
@@ -27,10 +27,12 @@
TDirectiveHandler::TDirectiveHandler(TExtensionBehavior& extBehavior,
TDiagnostics& diagnostics,
- int& shaderVersion)
+ int& shaderVersion,
+ bool debugShaderPrecisionSupported)
: mExtensionBehavior(extBehavior),
mDiagnostics(diagnostics),
- mShaderVersion(shaderVersion)
+ mShaderVersion(shaderVersion),
+ mDebugShaderPrecisionSupported(debugShaderPrecisionSupported)
{
}
@@ -65,6 +67,7 @@
{
const char kOptimize[] = "optimize";
const char kDebug[] = "debug";
+ const char kDebugShaderPrecision[] = "webgl_debug_shader_precision";
const char kOn[] = "on";
const char kOff[] = "off";
@@ -81,6 +84,12 @@
else if (value == kOff) mPragma.debug = false;
else invalidValue = true;
}
+ else if (name == kDebugShaderPrecision && mDebugShaderPrecisionSupported)
+ {
+ if (value == kOn) mPragma.debugShaderPrecision = true;
+ else if (value == kOff) mPragma.debugShaderPrecision = false;
+ else invalidValue = true;
+ }
else
{
mDiagnostics.report(pp::Diagnostics::PP_UNRECOGNIZED_PRAGMA, loc, name);
diff --git a/src/compiler/translator/DirectiveHandler.h b/src/compiler/translator/DirectiveHandler.h
index 5b591ab..70f6665 100644
--- a/src/compiler/translator/DirectiveHandler.h
+++ b/src/compiler/translator/DirectiveHandler.h
@@ -18,7 +18,8 @@
public:
TDirectiveHandler(TExtensionBehavior& extBehavior,
TDiagnostics& diagnostics,
- int& shaderVersion);
+ int& shaderVersion,
+ bool debugShaderPrecisionSupported);
virtual ~TDirectiveHandler();
const TPragma& pragma() const { return mPragma; }
@@ -44,6 +45,7 @@
TExtensionBehavior& mExtensionBehavior;
TDiagnostics& mDiagnostics;
int& mShaderVersion;
+ bool mDebugShaderPrecisionSupported;
};
#endif // COMPILER_TRANSLATOR_DIRECTIVEHANDLER_H_
diff --git a/src/compiler/translator/EmulatePrecision.cpp b/src/compiler/translator/EmulatePrecision.cpp
new file mode 100644
index 0000000..9f77261
--- /dev/null
+++ b/src/compiler/translator/EmulatePrecision.cpp
@@ -0,0 +1,497 @@
+//
+// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+
+#include "compiler/translator/EmulatePrecision.h"
+
+namespace
+{
+
+static void writeVectorPrecisionEmulationHelpers(
+ TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size)
+{
+ std::stringstream vecTypeStrStr;
+ if (outputLanguage == SH_ESSL_OUTPUT)
+ vecTypeStrStr << "highp ";
+ vecTypeStrStr << "vec" << size;
+ std::string vecType = vecTypeStrStr.str();
+
+ sink <<
+ vecType << " angle_frm(in " << vecType << " v) {\n"
+ " v = clamp(v, -65504.0, 65504.0);\n"
+ " " << vecType << " exponent = floor(log2(abs(v) + 1e-30)) - 10.0;\n"
+ " bvec" << size << " isNonZero = greaterThanEqual(exponent, vec" << size << "(-25.0));\n"
+ " v = v * exp2(-exponent);\n"
+ " v = sign(v) * floor(abs(v));\n"
+ " return v * exp2(exponent) * vec" << size << "(isNonZero);\n"
+ "}\n";
+
+ sink <<
+ vecType << " angle_frl(in " << vecType << " v) {\n"
+ " v = clamp(v, -2.0, 2.0);\n"
+ " v = v * 256.0;\n"
+ " v = sign(v) * floor(abs(v));\n"
+ " return v * 0.00390625;\n"
+ "}\n";
+}
+
+static void writeMatrixPrecisionEmulationHelper(
+ TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size, const char *functionName)
+{
+ std::stringstream matTypeStrStr;
+ if (outputLanguage == SH_ESSL_OUTPUT)
+ matTypeStrStr << "highp ";
+ matTypeStrStr << "mat" << size;
+ std::string matType = matTypeStrStr.str();
+
+ sink << matType << " " << functionName << "(in " << matType << " m) {\n"
+ " " << matType << " rounded;\n";
+
+ for (unsigned int i = 0; i < size; ++i)
+ {
+ sink << " rounded[" << i << "] = " << functionName << "(m[" << i << "]);\n";
+ }
+
+ sink << " return rounded;\n"
+ "}\n";
+}
+
+static void writeCommonPrecisionEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
+{
+ // Write the angle_frm functions that round floating point numbers to
+ // half precision, and angle_frl functions that round them to minimum lowp
+ // precision.
+
+ // Unoptimized version of angle_frm for single floats:
+ //
+ // int webgl_maxNormalExponent(in int exponentBits) {
+ // int possibleExponents = int(exp2(float(exponentBits)));
+ // int exponentBias = possibleExponents / 2 - 1;
+ // int allExponentBitsOne = possibleExponents - 1;
+ // return (allExponentBitsOne - 1) - exponentBias;
+ // }
+ //
+ // float angle_frm(in float x) {
+ // int mantissaBits = 10;
+ // int exponentBits = 5;
+ // float possibleMantissas = exp2(float(mantissaBits));
+ // float mantissaMax = 2.0 - 1.0 / possibleMantissas;
+ // int maxNE = webgl_maxNormalExponent(exponentBits);
+ // float max = exp2(float(maxNE)) * mantissaMax;
+ // if (x > max) {
+ // return max;
+ // }
+ // if (x < -max) {
+ // return -max;
+ // }
+ // float exponent = floor(log2(abs(x)));
+ // if (abs(x) == 0.0 || exponent < -float(maxNE)) {
+ // return 0.0 * sign(x)
+ // }
+ // x = x * exp2(-(exponent - float(mantissaBits)));
+ // x = sign(x) * floor(abs(x));
+ // return x * exp2(exponent - float(mantissaBits));
+ // }
+
+ // All numbers with a magnitude less than 2^-15 are subnormal, and are
+ // flushed to zero.
+
+ // Note the constant numbers below:
+ // a) 65504 is the maximum possible mantissa (1.1111111111 in binary) times
+ // 2^15, the maximum normal exponent.
+ // b) 10.0 is the number of mantissa bits.
+ // c) -25.0 is the minimum normal half-float exponent -15.0 minus the number
+ // of mantissa bits.
+ // d) + 1e-30 is to make sure the argument of log2() won't be zero. It can
+ // only affect the result of log2 on x where abs(x) < 1e-22. Since these
+ // numbers will be flushed to zero either way (2^-15 is the smallest
+ // normal positive number), this does not introduce any error.
+
+ std::string floatType = "float";
+ if (outputLanguage == SH_ESSL_OUTPUT)
+ floatType = "highp float";
+
+ sink <<
+ floatType << " angle_frm(in " << floatType << " x) {\n"
+ " x = clamp(x, -65504.0, 65504.0);\n"
+ " " << floatType << " exponent = floor(log2(abs(x) + 1e-30)) - 10.0;\n"
+ " bool isNonZero = (exponent >= -25.0);\n"
+ " x = x * exp2(-exponent);\n"
+ " x = sign(x) * floor(abs(x));\n"
+ " return x * exp2(exponent) * float(isNonZero);\n"
+ "}\n";
+
+ sink <<
+ floatType << " angle_frl(in " << floatType << " x) {\n"
+ " x = clamp(x, -2.0, 2.0);\n"
+ " x = x * 256.0;\n"
+ " x = sign(x) * floor(abs(x));\n"
+ " return x * 0.00390625;\n"
+ "}\n";
+
+ writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 2);
+ writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 3);
+ writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 4);
+ for (unsigned int size = 2; size <= 4; ++size)
+ {
+ writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frm");
+ writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frl");
+ }
+}
+
+static void writeCompoundAssignmentPrecisionEmulation(
+ TInfoSinkBase& sink, ShShaderOutput outputLanguage,
+ const char *lType, const char *rType, const char *opStr, const char *opNameStr)
+{
+ std::string lTypeStr = lType;
+ std::string rTypeStr = rType;
+ if (outputLanguage == SH_ESSL_OUTPUT)
+ {
+ std::stringstream lTypeStrStr;
+ lTypeStrStr << "highp " << lType;
+ lTypeStr = lTypeStrStr.str();
+ std::stringstream rTypeStrStr;
+ rTypeStrStr << "highp " << rType;
+ rTypeStr = rTypeStrStr.str();
+ }
+
+ // Note that y should be passed through angle_frm at the function call site,
+ // but x can't be passed through angle_frm there since it is an inout parameter.
+ // So only pass x and the result through angle_frm here.
+ sink <<
+ lTypeStr << " angle_compound_" << opNameStr << "_frm(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
+ " x = angle_frm(angle_frm(x) " << opStr << " y);\n"
+ " return x;\n"
+ "}\n";
+ sink <<
+ lTypeStr << " angle_compound_" << opNameStr << "_frl(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
+ " x = angle_frl(angle_frm(x) " << opStr << " y);\n"
+ " return x;\n"
+ "}\n";
+}
+
+const char *getFloatTypeStr(const TType& type)
+{
+ switch (type.getNominalSize())
+ {
+ case 1:
+ return "float";
+ case 2:
+ return type.getSecondarySize() > 1 ? "mat2" : "vec2";
+ case 3:
+ return type.getSecondarySize() > 1 ? "mat3" : "vec3";
+ case 4:
+ return type.getSecondarySize() > 1 ? "mat4" : "vec4";
+ default:
+ UNREACHABLE();
+ return NULL;
+ }
+}
+
+bool canRoundFloat(const TType &type)
+{
+ return type.getBasicType() == EbtFloat && !type.isNonSquareMatrix() && !type.isArray() &&
+ (type.getPrecision() == EbpLow || type.getPrecision() == EbpMedium);
+}
+
+TIntermAggregate *createInternalFunctionCallNode(TString name, TIntermNode *child)
+{
+ TIntermAggregate *callNode = new TIntermAggregate();
+ callNode->setOp(EOpInternalFunctionCall);
+ callNode->setName(name);
+ callNode->getSequence()->push_back(child);
+ return callNode;
+}
+
+TIntermAggregate *createRoundingFunctionCallNode(TIntermTyped *roundedChild)
+{
+ TString roundFunctionName;
+ if (roundedChild->getPrecision() == EbpMedium)
+ roundFunctionName = "angle_frm";
+ else
+ roundFunctionName = "angle_frl";
+ return createInternalFunctionCallNode(roundFunctionName, roundedChild);
+}
+
+TIntermAggregate *createCompoundAssignmentFunctionCallNode(TIntermTyped *left, TIntermTyped *right, const char *opNameStr)
+{
+ std::stringstream strstr;
+ if (left->getPrecision() == EbpMedium)
+ strstr << "angle_compound_" << opNameStr << "_frm";
+ else
+ strstr << "angle_compound_" << opNameStr << "_frl";
+ TString functionName = strstr.str().c_str();
+ TIntermAggregate *callNode = createInternalFunctionCallNode(functionName, left);
+ callNode->getSequence()->push_back(right);
+ return callNode;
+}
+
+} // namespace anonymous
+
+EmulatePrecision::EmulatePrecision()
+ : TIntermTraverser(true, true, true),
+ mDeclaringVariables(false),
+ mInLValue(false),
+ mInFunctionCallOutParameter(false)
+{}
+
+void EmulatePrecision::visitSymbol(TIntermSymbol *node)
+{
+ if (canRoundFloat(node->getType()) &&
+ !mDeclaringVariables && !mInLValue && !mInFunctionCallOutParameter)
+ {
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createRoundingFunctionCallNode(node);
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
+ }
+}
+
+
+bool EmulatePrecision::visitBinary(Visit visit, TIntermBinary *node)
+{
+ bool visitChildren = true;
+
+ if (node->isAssignment())
+ {
+ if (visit == PreVisit)
+ mInLValue = true;
+ else if (visit == InVisit)
+ mInLValue = false;
+ }
+
+ TOperator op = node->getOp();
+
+ // RHS of initialize is not being declared.
+ if (op == EOpInitialize && visit == InVisit)
+ mDeclaringVariables = false;
+
+ if ((op == EOpIndexDirectStruct || op == EOpVectorSwizzle) && visit == InVisit)
+ visitChildren = false;
+
+ if (visit != PreVisit)
+ return visitChildren;
+
+ const TType& type = node->getType();
+ bool roundFloat = canRoundFloat(type);
+
+ if (roundFloat) {
+ switch (op) {
+ // Math operators that can result in a float may need to apply rounding to the return
+ // value. Note that in the case of assignment, the rounding is applied to its return
+ // value here, not the value being assigned.
+ case EOpAssign:
+ case EOpAdd:
+ case EOpSub:
+ case EOpMul:
+ case EOpDiv:
+ case EOpVectorTimesScalar:
+ case EOpVectorTimesMatrix:
+ case EOpMatrixTimesVector:
+ case EOpMatrixTimesScalar:
+ case EOpMatrixTimesMatrix:
+ {
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createRoundingFunctionCallNode(node);
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
+ break;
+ }
+
+ // Compound assignment cases need to replace the operator with a function call.
+ case EOpAddAssign:
+ {
+ mEmulateCompoundAdd.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "add");
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
+ break;
+ }
+ case EOpSubAssign:
+ {
+ mEmulateCompoundSub.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "sub");
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
+ break;
+ }
+ case EOpMulAssign:
+ case EOpVectorTimesMatrixAssign:
+ case EOpVectorTimesScalarAssign:
+ case EOpMatrixTimesScalarAssign:
+ case EOpMatrixTimesMatrixAssign:
+ {
+ mEmulateCompoundMul.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "mul");
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
+ break;
+ }
+ case EOpDivAssign:
+ {
+ mEmulateCompoundDiv.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "div");
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
+ break;
+ }
+ default:
+ // The rest of the binary operations should not need precision emulation.
+ break;
+ }
+ }
+ return visitChildren;
+}
+
+bool EmulatePrecision::visitAggregate(Visit visit, TIntermAggregate *node)
+{
+ bool visitChildren = true;
+ switch (node->getOp())
+ {
+ case EOpSequence:
+ case EOpConstructStruct:
+ // No special handling
+ break;
+ case EOpFunction:
+ if (visit == PreVisit)
+ {
+ const TIntermSequence &sequence = *(node->getSequence());
+ TIntermSequence::const_iterator seqIter = sequence.begin();
+ TIntermAggregate *params = (*seqIter)->getAsAggregate();
+ ASSERT(params != NULL);
+ ASSERT(params->getOp() == EOpParameters);
+ mFunctionMap[node->getName()] = params->getSequence();
+ }
+ break;
+ case EOpPrototype:
+ if (visit == PreVisit)
+ mFunctionMap[node->getName()] = node->getSequence();
+ visitChildren = false;
+ break;
+ case EOpParameters:
+ visitChildren = false;
+ break;
+ case EOpInvariantDeclaration:
+ visitChildren = false;
+ break;
+ case EOpDeclaration:
+ // Variable declaration.
+ if (visit == PreVisit)
+ {
+ mDeclaringVariables = true;
+ }
+ else if (visit == InVisit)
+ {
+ mDeclaringVariables = true;
+ }
+ else
+ {
+ mDeclaringVariables = false;
+ }
+ break;
+ case EOpFunctionCall:
+ {
+ // Function call.
+ bool inFunctionMap = (mFunctionMap.find(node->getName()) != mFunctionMap.end());
+ if (visit == PreVisit)
+ {
+ if (canRoundFloat(node->getType()) && !inFunctionMap) {
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createRoundingFunctionCallNode(node);
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
+ }
+
+ if (inFunctionMap)
+ {
+ mSeqIterStack.push_back(mFunctionMap[node->getName()]->begin());
+ if (mSeqIterStack.back() != mFunctionMap[node->getName()]->end())
+ {
+ TQualifier qualifier = (*mSeqIterStack.back())->getAsTyped()->getQualifier();
+ mInFunctionCallOutParameter = (qualifier == EvqOut || qualifier == EvqInOut);
+ }
+ }
+ else
+ {
+ // The function is not user-defined - it is likely built-in texture function.
+ // Assume that those do not have out parameters.
+ mInFunctionCallOutParameter = false;
+ }
+ }
+ else if (visit == InVisit)
+ {
+ if (inFunctionMap)
+ {
+ ++mSeqIterStack.back();
+ TQualifier qualifier = (*mSeqIterStack.back())->getAsTyped()->getQualifier();
+ mInFunctionCallOutParameter = (qualifier == EvqOut || qualifier == EvqInOut);
+ }
+ }
+ else
+ {
+ if (inFunctionMap)
+ {
+ mSeqIterStack.pop_back();
+ mInFunctionCallOutParameter = false;
+ }
+ }
+ break;
+ }
+ default:
+ if (canRoundFloat(node->getType()) && visit == PreVisit)
+ {
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createRoundingFunctionCallNode(node);
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
+ }
+ break;
+ }
+ return visitChildren;
+}
+
+bool EmulatePrecision::visitUnary(Visit visit, TIntermUnary *node)
+{
+ switch (node->getOp())
+ {
+ case EOpNegative:
+ case EOpVectorLogicalNot:
+ case EOpLogicalNot:
+ break;
+ case EOpPostIncrement:
+ case EOpPostDecrement:
+ case EOpPreIncrement:
+ case EOpPreDecrement:
+ if (visit == PreVisit)
+ mInLValue = true;
+ else if (visit == PostVisit)
+ mInLValue = false;
+ break;
+ default:
+ if (canRoundFloat(node->getType()) && visit == PreVisit)
+ {
+ TIntermNode *parent = getParentNode();
+ TIntermNode *replacement = createRoundingFunctionCallNode(node);
+ mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
+ }
+ break;
+ }
+
+ return true;
+}
+
+void EmulatePrecision::writeEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
+{
+ // Other languages not yet supported
+ ASSERT(outputLanguage == SH_GLSL_OUTPUT || outputLanguage == SH_ESSL_OUTPUT);
+ writeCommonPrecisionEmulationHelpers(sink, outputLanguage);
+
+ EmulationSet::const_iterator it;
+ for (it = mEmulateCompoundAdd.begin(); it != mEmulateCompoundAdd.end(); it++)
+ writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "+", "add");
+ for (it = mEmulateCompoundSub.begin(); it != mEmulateCompoundSub.end(); it++)
+ writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "-", "sub");
+ for (it = mEmulateCompoundDiv.begin(); it != mEmulateCompoundDiv.end(); it++)
+ writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "/", "div");
+ for (it = mEmulateCompoundMul.begin(); it != mEmulateCompoundMul.end(); it++)
+ writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "*", "mul");
+}
+
diff --git a/src/compiler/translator/EmulatePrecision.h b/src/compiler/translator/EmulatePrecision.h
new file mode 100644
index 0000000..4b4c5b9
--- /dev/null
+++ b/src/compiler/translator/EmulatePrecision.h
@@ -0,0 +1,76 @@
+//
+// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+
+#ifndef COMPILER_TRANSLATOR_EMULATE_PRECISION_H_
+#define COMPILER_TRANSLATOR_EMULATE_PRECISION_H_
+
+#include "common/angleutils.h"
+#include "compiler/translator/InfoSink.h"
+#include "compiler/translator/IntermNode.h"
+#include "GLSLANG/ShaderLang.h"
+
+// This class gathers all compound assignments from the AST and can then write
+// the functions required for their precision emulation. This way there is no
+// need to write a huge number of variations of the emulated compound assignment
+// to every translated shader with emulation enabled.
+
+class EmulatePrecision : public TIntermTraverser
+{
+ public:
+ EmulatePrecision();
+
+ virtual void visitSymbol(TIntermSymbol *node);
+ virtual bool visitBinary(Visit visit, TIntermBinary *node);
+ virtual bool visitUnary(Visit visit, TIntermUnary *node);
+ virtual bool visitAggregate(Visit visit, TIntermAggregate *node);
+
+ void writeEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(EmulatePrecision);
+
+ struct TypePair
+ {
+ TypePair(const char *l, const char *r)
+ : lType(l), rType(r) { }
+
+ const char *lType;
+ const char *rType;
+ };
+
+ struct TypePairComparator
+ {
+ bool operator() (const TypePair& l, const TypePair& r) const
+ {
+ if (l.lType == r.lType)
+ return l.rType < r.rType;
+ return l.lType < r.lType;
+ }
+ };
+
+ typedef std::set<TypePair, TypePairComparator> EmulationSet;
+ EmulationSet mEmulateCompoundAdd;
+ EmulationSet mEmulateCompoundSub;
+ EmulationSet mEmulateCompoundMul;
+ EmulationSet mEmulateCompoundDiv;
+
+ // Stack of function call parameter iterators
+ std::vector<TIntermSequence::const_iterator> mSeqIterStack;
+
+ bool mDeclaringVariables;
+ bool mInLValue;
+ bool mInFunctionCallOutParameter;
+
+ struct TStringComparator
+ {
+ bool operator() (const TString& a, const TString& b) const { return a.compare(b) < 0; }
+ };
+
+ // Map from function names to their parameter sequences
+ std::map<TString, TIntermSequence*, TStringComparator> mFunctionMap;
+};
+
+#endif // COMPILER_TRANSLATOR_EMULATE_PRECISION_H_
diff --git a/src/compiler/translator/IntermNode.cpp b/src/compiler/translator/IntermNode.cpp
index aa0f31d..068b1e7 100644
--- a/src/compiler/translator/IntermNode.cpp
+++ b/src/compiler/translator/IntermNode.cpp
@@ -1181,3 +1181,29 @@
TString hashedName = stream.str();
return hashedName;
}
+
+void TIntermTraverser::updateTree()
+{
+ for (size_t ii = 0; ii < mReplacements.size(); ++ii)
+ {
+ const NodeUpdateEntry& entry = mReplacements[ii];
+ ASSERT(entry.parent);
+ bool replaced = entry.parent->replaceChildNode(
+ entry.original, entry.replacement);
+ ASSERT(replaced);
+
+ if (!entry.originalBecomesChildOfReplacement)
+ {
+ // In AST traversing, a parent is visited before its children.
+ // After we replace a node, if an immediate child is to
+ // be replaced, we need to make sure we don't update the replaced
+ // node; instead, we update the replacement node.
+ for (size_t jj = ii + 1; jj < mReplacements.size(); ++jj)
+ {
+ NodeUpdateEntry& entry2 = mReplacements[jj];
+ if (entry2.parent == entry.original)
+ entry2.parent = entry.replacement;
+ }
+ }
+ }
+}
diff --git a/src/compiler/translator/IntermNode.h b/src/compiler/translator/IntermNode.h
index 96fc304..cd3784c 100644
--- a/src/compiler/translator/IntermNode.h
+++ b/src/compiler/translator/IntermNode.h
@@ -33,6 +33,7 @@
EOpNull, // if in a node, should only mean a node is still being built
EOpSequence, // denotes a list of statements, or parameters, etc.
EOpFunctionCall,
+ EOpInternalFunctionCall, // Call to an internal helper function
EOpFunction, // For function definition
EOpParameters, // an aggregate listing the parameters to a function
@@ -741,12 +742,38 @@
const bool postVisit;
const bool rightToLeft;
+ // If traversers need to replace nodes, they can add the replacements in
+ // mReplacements during traversal and the user of the traverser should call
+ // this function after traversal to perform them.
+ void updateTree();
+
protected:
int mDepth;
int mMaxDepth;
// All the nodes from root to the current node's parent during traversing.
TVector<TIntermNode *> mPath;
+
+ struct NodeUpdateEntry
+ {
+ NodeUpdateEntry(TIntermNode *_parent,
+ TIntermNode *_original,
+ TIntermNode *_replacement,
+ bool _originalBecomesChildOfReplacement)
+ : parent(_parent),
+ original(_original),
+ replacement(_replacement),
+ originalBecomesChildOfReplacement(_originalBecomesChildOfReplacement) {}
+
+ TIntermNode *parent;
+ TIntermNode *original;
+ TIntermNode *replacement;
+ bool originalBecomesChildOfReplacement;
+ };
+
+ // During traversing, save all the changes that need to happen into
+ // mReplacements, then do them by calling updateTree().
+ std::vector<NodeUpdateEntry> mReplacements;
};
//
diff --git a/src/compiler/translator/OutputESSL.cpp b/src/compiler/translator/OutputESSL.cpp
index 65635af..7df69dd 100644
--- a/src/compiler/translator/OutputESSL.cpp
+++ b/src/compiler/translator/OutputESSL.cpp
@@ -11,8 +11,10 @@
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable,
- int shaderVersion)
- : TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable, shaderVersion)
+ int shaderVersion,
+ bool forceHighp)
+ : TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable, shaderVersion),
+ mForceHighp(forceHighp)
{
}
@@ -22,6 +24,9 @@
return false;
TInfoSinkBase& out = objSink();
- out << getPrecisionString(precision);
+ if (mForceHighp)
+ out << getPrecisionString(EbpHigh);
+ else
+ out << getPrecisionString(precision);
return true;
}
diff --git a/src/compiler/translator/OutputESSL.h b/src/compiler/translator/OutputESSL.h
index 9934493..813f1e9 100644
--- a/src/compiler/translator/OutputESSL.h
+++ b/src/compiler/translator/OutputESSL.h
@@ -17,10 +17,13 @@
ShHashFunction64 hashFunction,
NameMap& nameMap,
TSymbolTable& symbolTable,
- int shaderVersion);
+ int shaderVersion,
+ bool forceHighp);
protected:
virtual bool writeVariablePrecision(TPrecision precision);
+private:
+ bool mForceHighp;
};
#endif // COMPILER_TRANSLATOR_OUTPUTESSL_H_
diff --git a/src/compiler/translator/OutputGLSLBase.cpp b/src/compiler/translator/OutputGLSLBase.cpp
index ed59096..35de15c 100644
--- a/src/compiler/translator/OutputGLSLBase.cpp
+++ b/src/compiler/translator/OutputGLSLBase.cpp
@@ -622,6 +622,15 @@
else
out << ")";
break;
+ case EOpInternalFunctionCall:
+ // Function call to an internal helper function.
+ if (visit == PreVisit)
+ out << node->getName() << "(";
+ else if (visit == InVisit)
+ out << ", ";
+ else
+ out << ")";
+ break;
case EOpParameters:
// Function parameters.
ASSERT(visit == PreVisit);
diff --git a/src/compiler/translator/ParseContext.h b/src/compiler/translator/ParseContext.h
index 90b209b..ed4b7b4 100644
--- a/src/compiler/translator/ParseContext.h
+++ b/src/compiler/translator/ParseContext.h
@@ -25,7 +25,7 @@
// they can be passed to the parser without needing a global.
//
struct TParseContext {
- TParseContext(TSymbolTable& symt, TExtensionBehavior& ext, TIntermediate& interm, sh::GLenum type, ShShaderSpec spec, int options, bool checksPrecErrors, const char* sourcePath, TInfoSink& is) :
+ TParseContext(TSymbolTable& symt, TExtensionBehavior& ext, TIntermediate& interm, sh::GLenum type, ShShaderSpec spec, int options, bool checksPrecErrors, const char* sourcePath, TInfoSink& is, bool debugShaderPrecisionSupported) :
intermediate(interm),
symbolTable(symt),
shaderType(type),
@@ -42,7 +42,7 @@
defaultBlockStorage(EbsShared),
diagnostics(is),
shaderVersion(100),
- directiveHandler(ext, diagnostics, shaderVersion),
+ directiveHandler(ext, diagnostics, shaderVersion, debugShaderPrecisionSupported),
preprocessor(&diagnostics, &directiveHandler),
scanner(NULL) { }
TIntermediate& intermediate; // to hold and build a parse tree
diff --git a/src/compiler/translator/Pragma.h b/src/compiler/translator/Pragma.h
index d47c5ae..57b1134 100644
--- a/src/compiler/translator/Pragma.h
+++ b/src/compiler/translator/Pragma.h
@@ -18,11 +18,14 @@
// By default optimization is turned on and debug is turned off.
- TPragma() : optimize(true), debug(false) { }
- TPragma(bool o, bool d) : optimize(o), debug(d) { }
+ // Precision emulation is turned on by default, but has no effect unless
+ // the extension is enabled.
+ TPragma() : optimize(true), debug(false), debugShaderPrecision(true) { }
+ TPragma(bool o, bool d) : optimize(o), debug(d), debugShaderPrecision(true) { }
bool optimize;
bool debug;
+ bool debugShaderPrecision;
STDGL stdgl;
};
diff --git a/src/compiler/translator/ShaderLang.cpp b/src/compiler/translator/ShaderLang.cpp
index 0d6a1d6..ebbd68a 100644
--- a/src/compiler/translator/ShaderLang.cpp
+++ b/src/compiler/translator/ShaderLang.cpp
@@ -153,6 +153,7 @@
resources->EXT_draw_buffers = 0;
resources->EXT_frag_depth = 0;
resources->EXT_shader_texture_lod = 0;
+ resources->WEBGL_debug_shader_precision = 0;
resources->NV_draw_buffers = 0;
diff --git a/src/compiler/translator/TranslatorESSL.cpp b/src/compiler/translator/TranslatorESSL.cpp
index dcbf3ce..e75eb90 100644
--- a/src/compiler/translator/TranslatorESSL.cpp
+++ b/src/compiler/translator/TranslatorESSL.cpp
@@ -6,6 +6,7 @@
#include "compiler/translator/TranslatorESSL.h"
+#include "compiler/translator/EmulatePrecision.h"
#include "compiler/translator/OutputESSL.h"
#include "angle_gl.h"
@@ -21,6 +22,16 @@
// Write built-in extension behaviors.
writeExtensionBehavior();
+ bool precisionEmulation = getResources().WEBGL_debug_shader_precision && getPragma().debugShaderPrecision;
+
+ if (precisionEmulation)
+ {
+ EmulatePrecision emulatePrecision;
+ root->traverse(&emulatePrecision);
+ emulatePrecision.updateTree();
+ emulatePrecision.writeEmulationHelpers(sink, SH_ESSL_OUTPUT);
+ }
+
// Write emulated built-in functions if needed.
getBuiltInFunctionEmulator().OutputEmulatedFunctionDefinition(
sink, getShaderType() == GL_FRAGMENT_SHADER);
@@ -29,7 +40,7 @@
getArrayBoundsClamper().OutputClampingFunctionDefinition(sink);
// Write translated shader.
- TOutputESSL outputESSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable(), getShaderVersion());
+ TOutputESSL outputESSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable(), getShaderVersion(), precisionEmulation);
root->traverse(&outputESSL);
}
diff --git a/src/compiler/translator/TranslatorGLSL.cpp b/src/compiler/translator/TranslatorGLSL.cpp
index 6acbf7c..1c243b7 100644
--- a/src/compiler/translator/TranslatorGLSL.cpp
+++ b/src/compiler/translator/TranslatorGLSL.cpp
@@ -6,9 +6,11 @@
#include "compiler/translator/TranslatorGLSL.h"
+#include "compiler/translator/EmulatePrecision.h"
#include "compiler/translator/OutputGLSL.h"
#include "compiler/translator/VersionGLSL.h"
+
TranslatorGLSL::TranslatorGLSL(sh::GLenum type, ShShaderSpec spec)
: TCompiler(type, spec, SH_GLSL_OUTPUT) {
}
@@ -24,6 +26,16 @@
// Write extension behaviour as needed
writeExtensionBehavior();
+ bool precisionEmulation = getResources().WEBGL_debug_shader_precision && getPragma().debugShaderPrecision;
+
+ if (precisionEmulation)
+ {
+ EmulatePrecision emulatePrecision;
+ root->traverse(&emulatePrecision);
+ emulatePrecision.updateTree();
+ emulatePrecision.writeEmulationHelpers(sink, SH_GLSL_OUTPUT);
+ }
+
// Write emulated built-in functions if needed.
getBuiltInFunctionEmulator().OutputEmulatedFunctionDefinition(
sink, false);
diff --git a/src/compiler/translator/Types.h b/src/compiler/translator/Types.h
index c4208ba..2f6fb5f 100644
--- a/src/compiler/translator/Types.h
+++ b/src/compiler/translator/Types.h
@@ -325,6 +325,10 @@
{
return primarySize > 1 && secondarySize > 1;
}
+ bool isNonSquareMatrix() const
+ {
+ return isMatrix() && primarySize != secondarySize;
+ }
bool isArray() const
{
return array ? true : false;
diff --git a/src/compiler/translator/UnfoldShortCircuitAST.cpp b/src/compiler/translator/UnfoldShortCircuitAST.cpp
index 29c4397..d548d42 100644
--- a/src/compiler/translator/UnfoldShortCircuitAST.cpp
+++ b/src/compiler/translator/UnfoldShortCircuitAST.cpp
@@ -50,32 +50,8 @@
}
if (replacement)
{
- replacements.push_back(
- NodeUpdateEntry(getParentNode(), node, replacement));
+ mReplacements.push_back(
+ NodeUpdateEntry(getParentNode(), node, replacement, false));
}
return true;
}
-
-void UnfoldShortCircuitAST::updateTree()
-{
- for (size_t ii = 0; ii < replacements.size(); ++ii)
- {
- const NodeUpdateEntry& entry = replacements[ii];
- ASSERT(entry.parent);
- bool replaced = entry.parent->replaceChildNode(
- entry.original, entry.replacement);
- ASSERT(replaced);
-
- // In AST traversing, a parent is visited before its children.
- // After we replace a node, if an immediate child is to
- // be replaced, we need to make sure we don't update the replaced
- // node; instead, we update the replacement node.
- for (size_t jj = ii + 1; jj < replacements.size(); ++jj)
- {
- NodeUpdateEntry& entry2 = replacements[jj];
- if (entry2.parent == entry.original)
- entry2.parent = entry.replacement;
- }
- }
-}
-
diff --git a/src/compiler/translator/UnfoldShortCircuitAST.h b/src/compiler/translator/UnfoldShortCircuitAST.h
index 3544578..1ae36d3 100644
--- a/src/compiler/translator/UnfoldShortCircuitAST.h
+++ b/src/compiler/translator/UnfoldShortCircuitAST.h
@@ -24,27 +24,7 @@
virtual bool visitBinary(Visit visit, TIntermBinary *);
- void updateTree();
-
private:
- struct NodeUpdateEntry
- {
- NodeUpdateEntry(TIntermNode *_parent,
- TIntermNode *_original,
- TIntermNode *_replacement)
- : parent(_parent),
- original(_original),
- replacement(_replacement) {}
-
- TIntermNode *parent;
- TIntermNode *original;
- TIntermNode *replacement;
- };
-
- // During traversing, save all the replacements that need to happen;
- // then replace them by calling updateNodes().
- std::vector<NodeUpdateEntry> replacements;
-
DISALLOW_COPY_AND_ASSIGN(UnfoldShortCircuitAST);
};