Hash :
daeac238
Author :
Date :
2021-05-08T22:09:38
Translator: Ensure structs and blocks are uniquely defined A new AST validation is added to ensure that the same TStructure or TInterfaceBlock is not redundantly defined. This helps with SPIR-V generation by allowing the id to be used as key in a hash map that looks up the corresponding SPIR-V type id. A bug is fixed where the Vulkan driver uniform declaration created two identical declarations for ANGLEDepthRangeParams. A number of other bugs are also fixed in this change, where if a variable declaration is eliminated (for example due to constant folding, or inactive interface variable removal) and it contained a struct specifier, the struct declaration was also removed. OutputGLSLBase had a hack where structs were declared on first encounter, which was incorrect as the scope of the declaration could change. Those bugs are fixed and this hack is removed. Bug: angleproject:2733 Bug: angleproject:4889 Bug: angleproject:5936 Change-Id: I8e13748c0bf552ae8b052249282769a1f0775603 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/2881942 Reviewed-by: Charlie Lao <cclao@google.com> Reviewed-by: Jamie Madill <jmadill@chromium.org> Commit-Queue: Shahbaz Youssefi <syoussefi@chromium.org>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
//
// Copyright 2019 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.
//
// TranslatorMetal:
// A GLSL-based translator that outputs shaders that fit GL_KHR_vulkan_glsl.
// It takes into account some considerations for Metal backend also.
// The shaders are then fed into glslang to spit out SPIR-V.
// See: https://www.khronos.org/registry/vulkan/specs/misc/GL_KHR_vulkan_glsl.txt
//
// The SPIR-V will then be translated to Metal Shading Language later in Metal backend.
//
#include "compiler/translator/TranslatorMetal.h"
#include "angle_gl.h"
#include "common/utilities.h"
#include "compiler/translator/OutputVulkanGLSLForMetal.h"
#include "compiler/translator/StaticType.h"
#include "compiler/translator/tree_ops/InitializeVariables.h"
#include "compiler/translator/tree_util/BuiltIn.h"
#include "compiler/translator/tree_util/DriverUniform.h"
#include "compiler/translator/tree_util/FindMain.h"
#include "compiler/translator/tree_util/FindSymbolNode.h"
#include "compiler/translator/tree_util/IntermNode_util.h"
#include "compiler/translator/tree_util/ReplaceArrayOfMatrixVarying.h"
#include "compiler/translator/tree_util/ReplaceVariable.h"
#include "compiler/translator/tree_util/RunAtTheEndOfShader.h"
#include "compiler/translator/util.h"
namespace sh
{
namespace mtl
{
/** extern */
const char kCoverageMaskEnabledConstName[] = "ANGLECoverageMaskEnabled";
const char kRasterizerDiscardEnabledConstName[] = "ANGLERasterizerDisabled";
} // namespace mtl
namespace
{
// Metal specific driver uniforms
constexpr const char kHalfRenderArea[] = "halfRenderArea";
constexpr const char kFlipXY[] = "flipXY";
constexpr const char kNegFlipXY[] = "negFlipXY";
constexpr const char kCoverageMask[] = "coverageMask";
constexpr ImmutableString kSampleMaskWriteFuncName = ImmutableString("ANGLEWriteSampleMask");
// Unlike Vulkan having auto viewport flipping extension, in Metal we have to flip gl_Position.y
// manually.
// This operation performs flipping the gl_Position.y using this expression:
// gl_Position.y = gl_Position.y * negViewportScaleY
ANGLE_NO_DISCARD bool AppendVertexShaderPositionYCorrectionToMain(TCompiler *compiler,
TIntermBlock *root,
TSymbolTable *symbolTable,
TIntermTyped *negFlipY)
{
// Create a symbol reference to "gl_Position"
const TVariable *position = BuiltInVariable::gl_Position();
TIntermSymbol *positionRef = new TIntermSymbol(position);
// Create a swizzle to "gl_Position.y"
TVector<int> swizzleOffsetY;
swizzleOffsetY.push_back(1);
TIntermSwizzle *positionY = new TIntermSwizzle(positionRef, swizzleOffsetY);
// Create the expression "gl_Position.y * negFlipY"
TIntermBinary *inverseY = new TIntermBinary(EOpMul, positionY->deepCopy(), negFlipY);
// Create the assignment "gl_Position.y = gl_Position.y * negViewportScaleY
TIntermTyped *positionYLHS = positionY->deepCopy();
TIntermBinary *assignment = new TIntermBinary(TOperator::EOpAssign, positionYLHS, inverseY);
// Append the assignment as a statement at the end of the shader.
return RunAtTheEndOfShader(compiler, root, assignment, symbolTable);
}
// Initialize unused varying outputs.
ANGLE_NO_DISCARD bool InitializeUnusedOutputs(TIntermBlock *root,
TSymbolTable *symbolTable,
const InitVariableList &unusedVars)
{
if (unusedVars.empty())
{
return true;
}
TIntermSequence insertSequence;
for (const sh::ShaderVariable &var : unusedVars)
{
ASSERT(!var.active);
const TIntermSymbol *symbol = FindSymbolNode(root, var.name);
ASSERT(symbol);
TIntermSequence initCode;
CreateInitCode(symbol, false, false, &initCode, symbolTable);
insertSequence.insert(insertSequence.end(), initCode.begin(), initCode.end());
}
if (!insertSequence.empty())
{
TIntermFunctionDefinition *main = FindMain(root);
TIntermSequence *mainSequence = main->getBody()->getSequence();
// Insert init code at the start of main()
mainSequence->insert(mainSequence->begin(), insertSequence.begin(), insertSequence.end());
}
return true;
}
} // anonymous namespace
// class DriverUniformMetal
TFieldList *DriverUniformMetal::createUniformFields(TSymbolTable *symbolTable)
{
TFieldList *driverFieldList = DriverUniform::createUniformFields(symbolTable);
constexpr size_t kNumGraphicsDriverUniformsMetal = 4;
constexpr std::array<const char *, kNumGraphicsDriverUniformsMetal>
kGraphicsDriverUniformNamesMetal = {{kHalfRenderArea, kFlipXY, kNegFlipXY, kCoverageMask}};
const std::array<TType *, kNumGraphicsDriverUniformsMetal> kDriverUniformTypesMetal = {{
new TType(EbtFloat, 2), // halfRenderArea
new TType(EbtFloat, 2), // flipXY
new TType(EbtFloat, 2), // negFlipXY
new TType(EbtUInt), // kCoverageMask
}};
for (size_t uniformIndex = 0; uniformIndex < kNumGraphicsDriverUniformsMetal; ++uniformIndex)
{
TField *driverUniformField =
new TField(kDriverUniformTypesMetal[uniformIndex],
ImmutableString(kGraphicsDriverUniformNamesMetal[uniformIndex]),
TSourceLoc(), SymbolType::AngleInternal);
driverFieldList->push_back(driverUniformField);
}
return driverFieldList;
}
TIntermBinary *DriverUniformMetal::getHalfRenderAreaRef() const
{
return createDriverUniformRef(kHalfRenderArea);
}
TIntermBinary *DriverUniformMetal::getFlipXYRef() const
{
return createDriverUniformRef(kFlipXY);
}
TIntermBinary *DriverUniformMetal::getNegFlipXYRef() const
{
return createDriverUniformRef(kNegFlipXY);
}
TIntermSwizzle *DriverUniformMetal::getNegFlipYRef() const
{
// Create a swizzle to "negFlipXY.y"
TIntermBinary *negFlipXY = createDriverUniformRef(kNegFlipXY);
TVector<int> swizzleOffsetY = {1};
TIntermSwizzle *negFlipY = new TIntermSwizzle(negFlipXY, swizzleOffsetY);
return negFlipY;
}
TIntermBinary *DriverUniformMetal::getCoverageMaskFieldRef() const
{
return createDriverUniformRef(kCoverageMask);
}
TranslatorMetal::TranslatorMetal(sh::GLenum type, ShShaderSpec spec) : TranslatorVulkan(type, spec)
{}
bool TranslatorMetal::translate(TIntermBlock *root,
ShCompileOptions compileOptions,
PerformanceDiagnostics *perfDiagnostics)
{
TInfoSinkBase sink;
SpecConstMetal specConst(&getSymbolTable(), compileOptions, getShaderType());
DriverUniformMetal driverUniforms;
if (!TranslatorVulkan::translateImpl(sink, root, compileOptions, perfDiagnostics, &specConst,
&driverUniforms))
{
return false;
}
// Replace array of matrix varyings
if (!ReplaceArrayOfMatrixVaryings(this, root, &getSymbolTable()))
{
return false;
}
if (getShaderType() == GL_VERTEX_SHADER)
{
TIntermTyped *negFlipY = driverUniforms.getNegFlipYRef();
// Append gl_Position.y correction to main
if (!AppendVertexShaderPositionYCorrectionToMain(this, root, &getSymbolTable(), negFlipY))
{
return false;
}
// Insert rasterizer discard logic
if (!insertRasterizerDiscardLogic(sink, root))
{
return false;
}
}
else if (getShaderType() == GL_FRAGMENT_SHADER)
{
if (!insertSampleMaskWritingLogic(sink, root, &driverUniforms))
{
return false;
}
}
// Initialize unused varying outputs to avoid spirv-cross dead-code removing them in later
// stage. Only do this if SH_INIT_OUTPUT_VARIABLES is not specified.
if ((getShaderType() == GL_VERTEX_SHADER || getShaderType() == GL_GEOMETRY_SHADER_EXT) &&
(compileOptions & SH_INIT_OUTPUT_VARIABLES) == 0)
{
InitVariableList list;
for (const sh::ShaderVariable &var : mOutputVaryings)
{
if (!var.active)
{
list.push_back(var);
}
}
if (!InitializeUnusedOutputs(root, &getSymbolTable(), list))
{
return false;
}
}
// Write translated shader.
TOutputVulkanGLSL outputGLSL(sink, getArrayIndexClampingStrategy(), getHashFunction(),
getNameMap(), &getSymbolTable(), getShaderType(),
getShaderVersion(), getOutputType(), false, true, compileOptions);
root->traverse(&outputGLSL);
return compileToSpirv(sink);
}
// Metal needs to inverse the depth if depthRange is is reverse order, i.e. depth near > depth far
// This is achieved by multiply the depth value with scale value stored in
// driver uniform's depthRange.reserved
bool TranslatorMetal::transformDepthBeforeCorrection(TIntermBlock *root,
const DriverUniform *driverUniforms)
{
// Create a symbol reference to "gl_Position"
const TVariable *position = BuiltInVariable::gl_Position();
TIntermSymbol *positionRef = new TIntermSymbol(position);
// Create a swizzle to "gl_Position.z"
TVector<int> swizzleOffsetZ = {2};
TIntermSwizzle *positionZ = new TIntermSwizzle(positionRef, swizzleOffsetZ);
// Create a ref to "depthRange.reserved"
TIntermBinary *viewportZScale = driverUniforms->getDepthRangeReservedFieldRef();
// Create the expression "gl_Position.z * depthRange.reserved".
TIntermBinary *zScale = new TIntermBinary(EOpMul, positionZ->deepCopy(), viewportZScale);
// Create the assignment "gl_Position.z = gl_Position.z * depthRange.reserved"
TIntermTyped *positionZLHS = positionZ->deepCopy();
TIntermBinary *assignment = new TIntermBinary(TOperator::EOpAssign, positionZLHS, zScale);
// Append the assignment as a statement at the end of the shader.
return RunAtTheEndOfShader(this, root, assignment, &getSymbolTable());
}
// Add sample_mask writing to main, guarded by the specialization constant
// kCoverageMaskEnabledConstName
ANGLE_NO_DISCARD bool TranslatorMetal::insertSampleMaskWritingLogic(
TInfoSinkBase &sink,
TIntermBlock *root,
const DriverUniformMetal *driverUniforms)
{
// This transformation leaves the tree in an inconsistent state by using a variable that's
// defined in text, outside of the knowledge of the AST.
mValidateASTOptions.validateVariableReferences = false;
TSymbolTable *symbolTable = &getSymbolTable();
// Insert coverageMaskEnabled specialization constant and sample_mask writing function.
sink << "layout (constant_id=0) const bool " << mtl::kCoverageMaskEnabledConstName;
sink << " = false;\n";
sink << "void " << kSampleMaskWriteFuncName << "(uint mask)\n";
sink << "{\n";
sink << " if (" << mtl::kCoverageMaskEnabledConstName << ")\n";
sink << " {\n";
sink << " gl_SampleMask[0] = int(mask);\n";
sink << " }\n";
sink << "}\n";
// Create kCoverageMaskEnabledConstName and kSampleMaskWriteFuncName variable references.
TType *boolType = new TType(EbtBool);
boolType->setQualifier(EvqConst);
TVariable *coverageMaskEnabledVar =
new TVariable(symbolTable, ImmutableString(mtl::kCoverageMaskEnabledConstName), boolType,
SymbolType::AngleInternal);
TFunction *sampleMaskWriteFunc =
new TFunction(symbolTable, kSampleMaskWriteFuncName, SymbolType::AngleInternal,
StaticType::GetBasic<EbtVoid>(), false);
TType *uintType = new TType(EbtUInt);
TVariable *maskArg =
new TVariable(symbolTable, ImmutableString("mask"), uintType, SymbolType::AngleInternal);
sampleMaskWriteFunc->addParameter(maskArg);
// coverageMask
TIntermBinary *coverageMask = driverUniforms->getCoverageMaskFieldRef();
// Insert this code to the end of main()
// if (ANGLECoverageMaskEnabled)
// {
// ANGLEWriteSampleMask(ANGLEUniforms.coverageMask);
// }
TIntermSequence args;
args.push_back(coverageMask);
TIntermAggregate *callSampleMaskWriteFunc =
TIntermAggregate::CreateFunctionCall(*sampleMaskWriteFunc, &args);
TIntermBlock *callBlock = new TIntermBlock;
callBlock->appendStatement(callSampleMaskWriteFunc);
TIntermSymbol *coverageMaskEnabled = new TIntermSymbol(coverageMaskEnabledVar);
TIntermIfElse *ifCall = new TIntermIfElse(coverageMaskEnabled, callBlock, nullptr);
return RunAtTheEndOfShader(this, root, ifCall, symbolTable);
}
ANGLE_NO_DISCARD bool TranslatorMetal::insertRasterizerDiscardLogic(TInfoSinkBase &sink,
TIntermBlock *root)
{
// This transformation leaves the tree in an inconsistent state by using a variable that's
// defined in text, outside of the knowledge of the AST.
mValidateASTOptions.validateVariableReferences = false;
TSymbolTable *symbolTable = &getSymbolTable();
// Insert rasterizationDisabled specialization constant.
sink << "layout (constant_id=0) const bool " << mtl::kRasterizerDiscardEnabledConstName;
sink << " = false;\n";
// Create kRasterizerDiscardEnabledConstName variable reference.
TType *boolType = new TType(EbtBool);
boolType->setQualifier(EvqConst);
TVariable *discardEnabledVar =
new TVariable(symbolTable, ImmutableString(mtl::kRasterizerDiscardEnabledConstName),
boolType, SymbolType::AngleInternal);
// Insert this code to the end of main()
// if (ANGLERasterizerDisabled)
// {
// gl_Position = vec4(-3.0, -3.0, -3.0, 1.0);
// }
// Create a symbol reference to "gl_Position"
const TVariable *position = BuiltInVariable::gl_Position();
TIntermSymbol *positionRef = new TIntermSymbol(position);
// Create vec4(-3, -3, -3, 1):
auto vec4Type = new TType(EbtFloat, 4);
TIntermSequence vec4Args;
vec4Args.push_back(CreateFloatNode(-3.0f));
vec4Args.push_back(CreateFloatNode(-3.0f));
vec4Args.push_back(CreateFloatNode(-3.0f));
vec4Args.push_back(CreateFloatNode(1.0f));
TIntermAggregate *constVarConstructor =
TIntermAggregate::CreateConstructor(*vec4Type, &vec4Args);
// Create the assignment "gl_Position = vec4(-3, -3, -3, 1)"
TIntermBinary *assignment =
new TIntermBinary(TOperator::EOpAssign, positionRef->deepCopy(), constVarConstructor);
TIntermBlock *discardBlock = new TIntermBlock;
discardBlock->appendStatement(assignment);
TIntermSymbol *discardEnabled = new TIntermSymbol(discardEnabledVar);
TIntermIfElse *ifCall = new TIntermIfElse(discardEnabled, discardBlock, nullptr);
return RunAtTheEndOfShader(this, root, ifCall, symbolTable);
}
} // namespace sh