blob: b79e336fe5ac645ea55f1fc15dc4f6d6ceb0b50a [file] [log] [blame]
Olli Etuaho853dc1a2014-11-06 17:25:48 +02001//
2// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7#include "compiler/translator/EmulatePrecision.h"
8
9namespace
10{
11
12static void writeVectorPrecisionEmulationHelpers(
13 TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size)
14{
15 std::stringstream vecTypeStrStr;
16 if (outputLanguage == SH_ESSL_OUTPUT)
17 vecTypeStrStr << "highp ";
18 vecTypeStrStr << "vec" << size;
19 std::string vecType = vecTypeStrStr.str();
20
21 sink <<
22 vecType << " angle_frm(in " << vecType << " v) {\n"
23 " v = clamp(v, -65504.0, 65504.0);\n"
24 " " << vecType << " exponent = floor(log2(abs(v) + 1e-30)) - 10.0;\n"
25 " bvec" << size << " isNonZero = greaterThanEqual(exponent, vec" << size << "(-25.0));\n"
26 " v = v * exp2(-exponent);\n"
27 " v = sign(v) * floor(abs(v));\n"
28 " return v * exp2(exponent) * vec" << size << "(isNonZero);\n"
29 "}\n";
30
31 sink <<
32 vecType << " angle_frl(in " << vecType << " v) {\n"
33 " v = clamp(v, -2.0, 2.0);\n"
34 " v = v * 256.0;\n"
35 " v = sign(v) * floor(abs(v));\n"
36 " return v * 0.00390625;\n"
37 "}\n";
38}
39
40static void writeMatrixPrecisionEmulationHelper(
41 TInfoSinkBase& sink, ShShaderOutput outputLanguage, unsigned int size, const char *functionName)
42{
43 std::stringstream matTypeStrStr;
44 if (outputLanguage == SH_ESSL_OUTPUT)
45 matTypeStrStr << "highp ";
46 matTypeStrStr << "mat" << size;
47 std::string matType = matTypeStrStr.str();
48
49 sink << matType << " " << functionName << "(in " << matType << " m) {\n"
50 " " << matType << " rounded;\n";
51
52 for (unsigned int i = 0; i < size; ++i)
53 {
54 sink << " rounded[" << i << "] = " << functionName << "(m[" << i << "]);\n";
55 }
56
57 sink << " return rounded;\n"
58 "}\n";
59}
60
61static void writeCommonPrecisionEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
62{
63 // Write the angle_frm functions that round floating point numbers to
64 // half precision, and angle_frl functions that round them to minimum lowp
65 // precision.
66
67 // Unoptimized version of angle_frm for single floats:
68 //
69 // int webgl_maxNormalExponent(in int exponentBits) {
70 // int possibleExponents = int(exp2(float(exponentBits)));
71 // int exponentBias = possibleExponents / 2 - 1;
72 // int allExponentBitsOne = possibleExponents - 1;
73 // return (allExponentBitsOne - 1) - exponentBias;
74 // }
75 //
76 // float angle_frm(in float x) {
77 // int mantissaBits = 10;
78 // int exponentBits = 5;
79 // float possibleMantissas = exp2(float(mantissaBits));
80 // float mantissaMax = 2.0 - 1.0 / possibleMantissas;
81 // int maxNE = webgl_maxNormalExponent(exponentBits);
82 // float max = exp2(float(maxNE)) * mantissaMax;
83 // if (x > max) {
84 // return max;
85 // }
86 // if (x < -max) {
87 // return -max;
88 // }
89 // float exponent = floor(log2(abs(x)));
90 // if (abs(x) == 0.0 || exponent < -float(maxNE)) {
91 // return 0.0 * sign(x)
92 // }
93 // x = x * exp2(-(exponent - float(mantissaBits)));
94 // x = sign(x) * floor(abs(x));
95 // return x * exp2(exponent - float(mantissaBits));
96 // }
97
98 // All numbers with a magnitude less than 2^-15 are subnormal, and are
99 // flushed to zero.
100
101 // Note the constant numbers below:
102 // a) 65504 is the maximum possible mantissa (1.1111111111 in binary) times
103 // 2^15, the maximum normal exponent.
104 // b) 10.0 is the number of mantissa bits.
105 // c) -25.0 is the minimum normal half-float exponent -15.0 minus the number
106 // of mantissa bits.
107 // d) + 1e-30 is to make sure the argument of log2() won't be zero. It can
108 // only affect the result of log2 on x where abs(x) < 1e-22. Since these
109 // numbers will be flushed to zero either way (2^-15 is the smallest
110 // normal positive number), this does not introduce any error.
111
112 std::string floatType = "float";
113 if (outputLanguage == SH_ESSL_OUTPUT)
114 floatType = "highp float";
115
116 sink <<
117 floatType << " angle_frm(in " << floatType << " x) {\n"
118 " x = clamp(x, -65504.0, 65504.0);\n"
119 " " << floatType << " exponent = floor(log2(abs(x) + 1e-30)) - 10.0;\n"
120 " bool isNonZero = (exponent >= -25.0);\n"
121 " x = x * exp2(-exponent);\n"
122 " x = sign(x) * floor(abs(x));\n"
123 " return x * exp2(exponent) * float(isNonZero);\n"
124 "}\n";
125
126 sink <<
127 floatType << " angle_frl(in " << floatType << " x) {\n"
128 " x = clamp(x, -2.0, 2.0);\n"
129 " x = x * 256.0;\n"
130 " x = sign(x) * floor(abs(x));\n"
131 " return x * 0.00390625;\n"
132 "}\n";
133
134 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 2);
135 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 3);
136 writeVectorPrecisionEmulationHelpers(sink, outputLanguage, 4);
137 for (unsigned int size = 2; size <= 4; ++size)
138 {
139 writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frm");
140 writeMatrixPrecisionEmulationHelper(sink, outputLanguage, size, "angle_frl");
141 }
142}
143
144static void writeCompoundAssignmentPrecisionEmulation(
145 TInfoSinkBase& sink, ShShaderOutput outputLanguage,
146 const char *lType, const char *rType, const char *opStr, const char *opNameStr)
147{
148 std::string lTypeStr = lType;
149 std::string rTypeStr = rType;
150 if (outputLanguage == SH_ESSL_OUTPUT)
151 {
152 std::stringstream lTypeStrStr;
153 lTypeStrStr << "highp " << lType;
154 lTypeStr = lTypeStrStr.str();
155 std::stringstream rTypeStrStr;
156 rTypeStrStr << "highp " << rType;
157 rTypeStr = rTypeStrStr.str();
158 }
159
160 // Note that y should be passed through angle_frm at the function call site,
161 // but x can't be passed through angle_frm there since it is an inout parameter.
162 // So only pass x and the result through angle_frm here.
163 sink <<
164 lTypeStr << " angle_compound_" << opNameStr << "_frm(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
165 " x = angle_frm(angle_frm(x) " << opStr << " y);\n"
166 " return x;\n"
167 "}\n";
168 sink <<
169 lTypeStr << " angle_compound_" << opNameStr << "_frl(inout " << lTypeStr << " x, in " << rTypeStr << " y) {\n"
170 " x = angle_frl(angle_frm(x) " << opStr << " y);\n"
171 " return x;\n"
172 "}\n";
173}
174
175const char *getFloatTypeStr(const TType& type)
176{
177 switch (type.getNominalSize())
178 {
179 case 1:
180 return "float";
181 case 2:
Alexis Hetu07e57df2015-06-16 16:55:52 -0400182 switch(type.getSecondarySize())
183 {
184 case 1:
185 return "vec2";
186 case 2:
187 return "mat2";
188 case 3:
189 return "mat2x3";
190 case 4:
191 return "mat2x4";
192 default:
193 UNREACHABLE();
194 return NULL;
195 }
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200196 case 3:
Alexis Hetu07e57df2015-06-16 16:55:52 -0400197 switch(type.getSecondarySize())
198 {
199 case 1:
200 return "vec3";
201 case 2:
202 return "mat3x2";
203 case 3:
204 return "mat3";
205 case 4:
206 return "mat3x4";
207 default:
208 UNREACHABLE();
209 return NULL;
210 }
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200211 case 4:
Alexis Hetu07e57df2015-06-16 16:55:52 -0400212 switch(type.getSecondarySize())
213 {
214 case 1:
215 return "vec4";
216 case 2:
217 return "mat4x2";
218 case 3:
219 return "mat4x3";
220 case 4:
221 return "mat4";
222 default:
223 UNREACHABLE();
224 return NULL;
225 }
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200226 default:
227 UNREACHABLE();
228 return NULL;
229 }
230}
231
232bool canRoundFloat(const TType &type)
233{
234 return type.getBasicType() == EbtFloat && !type.isNonSquareMatrix() && !type.isArray() &&
235 (type.getPrecision() == EbpLow || type.getPrecision() == EbpMedium);
236}
237
238TIntermAggregate *createInternalFunctionCallNode(TString name, TIntermNode *child)
239{
240 TIntermAggregate *callNode = new TIntermAggregate();
241 callNode->setOp(EOpInternalFunctionCall);
242 callNode->setName(name);
243 callNode->getSequence()->push_back(child);
244 return callNode;
245}
246
247TIntermAggregate *createRoundingFunctionCallNode(TIntermTyped *roundedChild)
248{
249 TString roundFunctionName;
250 if (roundedChild->getPrecision() == EbpMedium)
251 roundFunctionName = "angle_frm";
252 else
253 roundFunctionName = "angle_frl";
254 return createInternalFunctionCallNode(roundFunctionName, roundedChild);
255}
256
257TIntermAggregate *createCompoundAssignmentFunctionCallNode(TIntermTyped *left, TIntermTyped *right, const char *opNameStr)
258{
259 std::stringstream strstr;
260 if (left->getPrecision() == EbpMedium)
261 strstr << "angle_compound_" << opNameStr << "_frm";
262 else
263 strstr << "angle_compound_" << opNameStr << "_frl";
264 TString functionName = strstr.str().c_str();
265 TIntermAggregate *callNode = createInternalFunctionCallNode(functionName, left);
266 callNode->getSequence()->push_back(right);
267 return callNode;
268}
269
Olli Etuaho1be88702015-01-19 16:56:44 +0200270bool parentUsesResult(TIntermNode* parent, TIntermNode* node)
271{
272 if (!parent)
273 {
274 return false;
275 }
276
277 TIntermAggregate *aggParent = parent->getAsAggregate();
278 // If the parent's op is EOpSequence, the result is not assigned anywhere,
279 // so rounding it is not needed. In particular, this can avoid a lot of
280 // unnecessary rounding of unused return values of assignment.
281 if (aggParent && aggParent->getOp() == EOpSequence)
282 {
283 return false;
284 }
285 if (aggParent && aggParent->getOp() == EOpComma && (aggParent->getSequence()->back() != node))
286 {
287 return false;
288 }
289 return true;
290}
291
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200292} // namespace anonymous
293
Olli Etuaho217fe6e2015-08-05 13:25:08 +0300294EmulatePrecision::EmulatePrecision(const TSymbolTable &symbolTable, int shaderVersion)
295 : TLValueTrackingTraverser(true, true, true, symbolTable, shaderVersion),
296 mDeclaringVariables(false)
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200297{}
298
299void EmulatePrecision::visitSymbol(TIntermSymbol *node)
300{
Olli Etuahoa26ad582015-08-04 13:51:47 +0300301 if (canRoundFloat(node->getType()) && !mDeclaringVariables && !isLValueRequiredHere())
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200302 {
303 TIntermNode *parent = getParentNode();
304 TIntermNode *replacement = createRoundingFunctionCallNode(node);
305 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
306 }
307}
308
309
310bool EmulatePrecision::visitBinary(Visit visit, TIntermBinary *node)
311{
312 bool visitChildren = true;
313
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200314 TOperator op = node->getOp();
315
316 // RHS of initialize is not being declared.
317 if (op == EOpInitialize && visit == InVisit)
318 mDeclaringVariables = false;
319
320 if ((op == EOpIndexDirectStruct || op == EOpVectorSwizzle) && visit == InVisit)
321 visitChildren = false;
322
323 if (visit != PreVisit)
324 return visitChildren;
325
326 const TType& type = node->getType();
327 bool roundFloat = canRoundFloat(type);
328
329 if (roundFloat) {
330 switch (op) {
331 // Math operators that can result in a float may need to apply rounding to the return
332 // value. Note that in the case of assignment, the rounding is applied to its return
333 // value here, not the value being assigned.
334 case EOpAssign:
335 case EOpAdd:
336 case EOpSub:
337 case EOpMul:
338 case EOpDiv:
339 case EOpVectorTimesScalar:
340 case EOpVectorTimesMatrix:
341 case EOpMatrixTimesVector:
342 case EOpMatrixTimesScalar:
343 case EOpMatrixTimesMatrix:
344 {
345 TIntermNode *parent = getParentNode();
Olli Etuaho1be88702015-01-19 16:56:44 +0200346 if (!parentUsesResult(parent, node))
347 {
348 break;
349 }
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200350 TIntermNode *replacement = createRoundingFunctionCallNode(node);
351 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
352 break;
353 }
354
355 // Compound assignment cases need to replace the operator with a function call.
356 case EOpAddAssign:
357 {
358 mEmulateCompoundAdd.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
359 TIntermNode *parent = getParentNode();
360 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "add");
361 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
362 break;
363 }
364 case EOpSubAssign:
365 {
366 mEmulateCompoundSub.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
367 TIntermNode *parent = getParentNode();
368 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "sub");
369 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
370 break;
371 }
372 case EOpMulAssign:
373 case EOpVectorTimesMatrixAssign:
374 case EOpVectorTimesScalarAssign:
375 case EOpMatrixTimesScalarAssign:
376 case EOpMatrixTimesMatrixAssign:
377 {
378 mEmulateCompoundMul.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
379 TIntermNode *parent = getParentNode();
380 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "mul");
381 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
382 break;
383 }
384 case EOpDivAssign:
385 {
386 mEmulateCompoundDiv.insert(TypePair(getFloatTypeStr(type), getFloatTypeStr(node->getRight()->getType())));
387 TIntermNode *parent = getParentNode();
388 TIntermNode *replacement = createCompoundAssignmentFunctionCallNode(node->getLeft(), node->getRight(), "div");
389 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, false));
390 break;
391 }
392 default:
393 // The rest of the binary operations should not need precision emulation.
394 break;
395 }
396 }
397 return visitChildren;
398}
399
400bool EmulatePrecision::visitAggregate(Visit visit, TIntermAggregate *node)
401{
402 bool visitChildren = true;
403 switch (node->getOp())
404 {
405 case EOpSequence:
406 case EOpConstructStruct:
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200407 case EOpFunction:
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200408 break;
409 case EOpPrototype:
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200410 visitChildren = false;
411 break;
412 case EOpParameters:
413 visitChildren = false;
414 break;
415 case EOpInvariantDeclaration:
416 visitChildren = false;
417 break;
418 case EOpDeclaration:
419 // Variable declaration.
420 if (visit == PreVisit)
421 {
422 mDeclaringVariables = true;
423 }
424 else if (visit == InVisit)
425 {
426 mDeclaringVariables = true;
427 }
428 else
429 {
430 mDeclaringVariables = false;
431 }
432 break;
433 case EOpFunctionCall:
434 {
435 // Function call.
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200436 if (visit == PreVisit)
437 {
Olli Etuaho1be88702015-01-19 16:56:44 +0200438 // User-defined function return values are not rounded, this relies on that
439 // calculations producing the value were rounded.
440 TIntermNode *parent = getParentNode();
Olli Etuahoa26ad582015-08-04 13:51:47 +0300441 if (canRoundFloat(node->getType()) && !isInFunctionMap(node) &&
442 parentUsesResult(parent, node))
Olli Etuaho1be88702015-01-19 16:56:44 +0200443 {
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200444 TIntermNode *replacement = createRoundingFunctionCallNode(node);
445 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
446 }
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200447 }
448 break;
449 }
450 default:
Olli Etuaho1be88702015-01-19 16:56:44 +0200451 TIntermNode *parent = getParentNode();
452 if (canRoundFloat(node->getType()) && visit == PreVisit && parentUsesResult(parent, node))
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200453 {
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200454 TIntermNode *replacement = createRoundingFunctionCallNode(node);
455 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
456 }
457 break;
458 }
459 return visitChildren;
460}
461
462bool EmulatePrecision::visitUnary(Visit visit, TIntermUnary *node)
463{
464 switch (node->getOp())
465 {
466 case EOpNegative:
467 case EOpVectorLogicalNot:
468 case EOpLogicalNot:
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200469 case EOpPostIncrement:
470 case EOpPostDecrement:
471 case EOpPreIncrement:
472 case EOpPreDecrement:
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200473 break;
474 default:
475 if (canRoundFloat(node->getType()) && visit == PreVisit)
476 {
477 TIntermNode *parent = getParentNode();
478 TIntermNode *replacement = createRoundingFunctionCallNode(node);
479 mReplacements.push_back(NodeUpdateEntry(parent, node, replacement, true));
480 }
481 break;
482 }
483
484 return true;
485}
486
487void EmulatePrecision::writeEmulationHelpers(TInfoSinkBase& sink, ShShaderOutput outputLanguage)
488{
489 // Other languages not yet supported
Zhenyao Mo05b6b7f2015-03-02 17:08:09 -0800490 ASSERT(outputLanguage == SH_GLSL_COMPATIBILITY_OUTPUT ||
Qingqing Dengad0d0792015-04-08 14:25:06 -0700491 IsGLSL130OrNewer(outputLanguage) ||
Zhenyao Mo05b6b7f2015-03-02 17:08:09 -0800492 outputLanguage == SH_ESSL_OUTPUT);
Olli Etuaho853dc1a2014-11-06 17:25:48 +0200493 writeCommonPrecisionEmulationHelpers(sink, outputLanguage);
494
495 EmulationSet::const_iterator it;
496 for (it = mEmulateCompoundAdd.begin(); it != mEmulateCompoundAdd.end(); it++)
497 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "+", "add");
498 for (it = mEmulateCompoundSub.begin(); it != mEmulateCompoundSub.end(); it++)
499 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "-", "sub");
500 for (it = mEmulateCompoundDiv.begin(); it != mEmulateCompoundDiv.end(); it++)
501 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "/", "div");
502 for (it = mEmulateCompoundMul.begin(); it != mEmulateCompoundMul.end(); it++)
503 writeCompoundAssignmentPrecisionEmulation(sink, outputLanguage, it->lType, it->rType, "*", "mul");
504}
505