blob: 42d6704c96cf535b4c8b4b213bb9ed8a2811c645 [file] [log] [blame]
//
//Copyright (C) 2016 Google, Inc.
//Copyright (C) 2016 LunarG, Inc.
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions
//are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//POSSIBILITY OF SUCH DAMAGE.
//
#include "hlslParseHelper.h"
#include "hlslScanContext.h"
#include "hlslGrammar.h"
#include "../glslang/MachineIndependent/Scan.h"
#include "../glslang/MachineIndependent/preprocessor/PpContext.h"
#include "../glslang/OSDependent/osinclude.h"
#include <cstdarg>
#include <algorithm>
namespace glslang {
HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool /*parsingBuiltins*/,
int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TInfoSink& infoSink,
bool forwardCompatible, EShMessages messages) :
TParseContextBase(symbolTable, interm, version, profile, spvVersion, language, infoSink, forwardCompatible, messages),
contextPragma(true, false), loopNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0),
postMainReturn(false),
limits(resources.limits),
afterEOF(false)
{
// ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
linkage = new TIntermAggregate;
globalUniformDefaults.clear();
globalUniformDefaults.layoutMatrix = ElmColumnMajor;
globalUniformDefaults.layoutPacking = ElpStd140;
globalBufferDefaults.clear();
globalBufferDefaults.layoutMatrix = ElmColumnMajor;
globalBufferDefaults.layoutPacking = ElpStd430;
globalInputDefaults.clear();
globalOutputDefaults.clear();
// "Shaders in the transform
// feedback capturing mode have an initial global default of
// layout(xfb_buffer = 0) out;"
if (language == EShLangVertex ||
language == EShLangTessControl ||
language == EShLangTessEvaluation ||
language == EShLangGeometry)
globalOutputDefaults.layoutXfbBuffer = 0;
if (language == EShLangGeometry)
globalOutputDefaults.layoutStream = 0;
}
HlslParseContext::~HlslParseContext()
{
}
void HlslParseContext::initializeExtensionBehavior()
{
TParseContextBase::initializeExtensionBehavior();
// HLSL allows #line by default.
extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
}
void HlslParseContext::setLimits(const TBuiltInResource& r)
{
resources = r;
intermediate.setLimits(resources);
}
//
// Parse an array of strings using the parser in HlslRules.
//
// Returns true for successful acceptance of the shader, false if any errors.
//
bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
{
currentScanner = &input;
ppContext.setInput(input, versionWillBeError);
HlslScanContext::fillInKeywordMap(); // TODO: right place, and include the delete too
HlslScanContext scanContext(*this, ppContext);
HlslGrammar grammar(scanContext, *this);
if (!grammar.parse())
{
// Print a message formated such that if you click on the message it will take you right to
// the line through most UIs.
const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
printf("\n%s(%i): error at column %i, HLSL translation failed.\n", sourceLoc.name, sourceLoc.line,
sourceLoc.column);
}
return numErrors == 0;
}
void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
{
if (pragmaCallback)
pragmaCallback(loc.line, tokens);
if (tokens.size() == 0)
return;
}
//
// Look at a '.' field selector string and change it into offsets
// for a vector or scalar
//
// Returns true if there is no error.
//
bool HlslParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields)
{
fields.num = (int)compString.size();
if (fields.num > 4) {
error(loc, "illegal vector field selection", compString.c_str(), "");
return false;
}
enum {
exyzw,
ergba,
estpq,
} fieldSet[4];
for (int i = 0; i < fields.num; ++i) {
switch (compString[i]) {
case 'x':
fields.offsets[i] = 0;
fieldSet[i] = exyzw;
break;
case 'r':
fields.offsets[i] = 0;
fieldSet[i] = ergba;
break;
case 's':
fields.offsets[i] = 0;
fieldSet[i] = estpq;
break;
case 'y':
fields.offsets[i] = 1;
fieldSet[i] = exyzw;
break;
case 'g':
fields.offsets[i] = 1;
fieldSet[i] = ergba;
break;
case 't':
fields.offsets[i] = 1;
fieldSet[i] = estpq;
break;
case 'z':
fields.offsets[i] = 2;
fieldSet[i] = exyzw;
break;
case 'b':
fields.offsets[i] = 2;
fieldSet[i] = ergba;
break;
case 'p':
fields.offsets[i] = 2;
fieldSet[i] = estpq;
break;
case 'w':
fields.offsets[i] = 3;
fieldSet[i] = exyzw;
break;
case 'a':
fields.offsets[i] = 3;
fieldSet[i] = ergba;
break;
case 'q':
fields.offsets[i] = 3;
fieldSet[i] = estpq;
break;
default:
error(loc, "illegal vector field selection", compString.c_str(), "");
return false;
}
}
for (int i = 0; i < fields.num; ++i) {
if (fields.offsets[i] >= vecSize) {
error(loc, "vector field selection out of range", compString.c_str(), "");
return false;
}
if (i > 0) {
if (fieldSet[i] != fieldSet[i - 1]) {
error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
return false;
}
}
}
return true;
}
//
// Used to output syntax, parsing, and semantic errors.
//
void HlslParseContext::outputMessage(const TSourceLoc& loc, const char* szReason,
const char* szToken,
const char* szExtraInfoFormat,
TPrefixType prefix, va_list args)
{
const int maxSize = MaxTokenLength + 200;
char szExtraInfo[maxSize];
safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, args);
infoSink.info.prefix(prefix);
infoSink.info.location(loc);
infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
if (prefix == EPrefixError) {
++numErrors;
}
}
void C_DECL HlslParseContext::error(const TSourceLoc& loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
if (messages & EShMsgOnlyPreprocessor)
return;
va_list args;
va_start(args, szExtraInfoFormat);
outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
va_end(args);
}
void C_DECL HlslParseContext::warn(const TSourceLoc& loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
if (suppressWarnings())
return;
va_list args;
va_start(args, szExtraInfoFormat);
outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
va_end(args);
}
void C_DECL HlslParseContext::ppError(const TSourceLoc& loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
va_list args;
va_start(args, szExtraInfoFormat);
outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixError, args);
va_end(args);
}
void C_DECL HlslParseContext::ppWarn(const TSourceLoc& loc, const char* szReason, const char* szToken,
const char* szExtraInfoFormat, ...)
{
va_list args;
va_start(args, szExtraInfoFormat);
outputMessage(loc, szReason, szToken, szExtraInfoFormat, EPrefixWarning, args);
va_end(args);
}
//
// Handle seeing a variable identifier in the grammar.
//
TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
{
if (symbol == nullptr)
symbol = symbolTable.find(*string);
if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
error(loc, "expected symbol, not user-defined type", string->c_str(), "");
return nullptr;
}
// Error check for requiring specific extensions present.
if (symbol && symbol->getNumExtensions())
requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
if (symbol && symbol->isReadOnly()) {
// All shared things containing an implicitly sized array must be copied up
// on first use, so that all future references will share its array structure,
// so that editing the implicit size will effect all nodes consuming it,
// and so that editing the implicit size won't change the shared one.
//
// If this is a variable or a block, check it and all it contains, but if this
// is a member of an anonymous block, check the whole block, as the whole block
// will need to be copied up if it contains an implicitly-sized array.
if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
makeEditable(symbol);
}
const TVariable* variable;
const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
TIntermTyped* node = nullptr;
if (anon) {
// It was a member of an anonymous container.
// Create a subtree for its dereference.
variable = anon->getAnonContainer().getAsVariable();
TIntermTyped* container = intermediate.addSymbol(*variable, loc);
TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
if (node->getType().hiddenMember())
error(loc, "member of nameless block was not redeclared", string->c_str(), "");
} else {
// Not a member of an anonymous container.
// The symbol table search was done in the lexical phase.
// See if it was a variable.
variable = symbol ? symbol->getAsVariable() : nullptr;
if (variable) {
if ((variable->getType().getBasicType() == EbtBlock ||
variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
variable = nullptr;
}
} else {
if (symbol)
error(loc, "variable name expected", string->c_str(), "");
}
// Recovery, if it wasn't found or was not a variable.
if (! variable)
variable = new TVariable(string, TType(EbtVoid));
if (variable->getType().getQualifier().isFrontEndConstant())
node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
else
node = intermediate.addSymbol(*variable, loc);
}
if (variable->getType().getQualifier().isIo())
intermediate.addIoAccessed(*string);
return node;
}
//
// Handle seeing a base[index] dereference in the grammar.
//
TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
{
TIntermTyped* result = nullptr;
int indexValue = 0;
if (index->getQualifier().storage == EvqConst) {
indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
checkIndex(loc, base->getType(), indexValue);
}
variableCheck(base);
if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
if (base->getAsSymbolNode())
error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
else
error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
} else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
return intermediate.foldDereference(base, indexValue, loc);
else {
// at least one of base and index is variable...
if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
handleIoResizeArrayAccess(loc, base);
if (index->getQualifier().storage == EvqConst) {
if (base->getType().isImplicitlySizedArray())
updateImplicitArraySize(loc, base, indexValue);
result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
} else {
result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
}
}
if (result == nullptr) {
// Insert dummy error-recovery result
result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
} else {
// Insert valid dereferenced result
TType newType(base->getType(), 0); // dereferenced type
if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
newType.getQualifier().storage = EvqConst;
else
newType.getQualifier().storage = EvqTemporary;
result->setType(newType);
}
return result;
}
void HlslParseContext::checkIndex(const TSourceLoc& /*loc*/, const TType& /*type*/, int& /*index*/)
{
// HLSL todo: any rules for index fixups?
}
// Make a shared symbol have a non-shared version that can be edited by the current
// compile, such that editing its type will not change the shared version and will
// effect all nodes sharing it.
void HlslParseContext::makeEditable(TSymbol*& symbol)
{
// copyUp() does a deep copy of the type.
symbol = symbolTable.copyUp(symbol);
// Also, see if it's tied to IO resizing
if (isIoResizeArray(symbol->getType()))
ioArraySymbolResizeList.push_back(symbol);
// Also, save it in the AST for linker use.
intermediate.addSymbolLinkageNode(linkage, *symbol);
}
TVariable* HlslParseContext::getEditableVariable(const char* name)
{
bool builtIn;
TSymbol* symbol = symbolTable.find(name, &builtIn);
if (builtIn)
makeEditable(symbol);
return symbol->getAsVariable();
}
// Return true if this is a geometry shader input array or tessellation control output array.
bool HlslParseContext::isIoResizeArray(const TType& type) const
{
return type.isArray() &&
((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
(language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
}
// If an array is not isIoResizeArray() but is an io array, make sure it has the right size
void HlslParseContext::fixIoArraySize(const TSourceLoc& loc, TType& type)
{
if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
return;
assert(! isIoResizeArray(type));
if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
return;
if (language == EShLangTessControl || language == EShLangTessEvaluation) {
if (type.getOuterArraySize() != resources.maxPatchVertices) {
if (type.isExplicitlySizedArray())
error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
type.changeOuterArraySize(resources.maxPatchVertices);
}
}
}
// Handle a dereference of a geometry shader input array or tessellation control output array.
// See ioArraySymbolResizeList comment in ParseHelper.h.
//
void HlslParseContext::handleIoResizeArrayAccess(const TSourceLoc& /*loc*/, TIntermTyped* base)
{
TIntermSymbol* symbolNode = base->getAsSymbolNode();
assert(symbolNode);
if (! symbolNode)
return;
// fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
if (symbolNode->getType().isImplicitlySizedArray()) {
int newSize = getIoArrayImplicitSize();
if (newSize > 0)
symbolNode->getWritableType().changeOuterArraySize(newSize);
}
}
// If there has been an input primitive declaration (geometry shader) or an output
// number of vertices declaration(tessellation shader), make sure all input array types
// match it in size. Types come either from nodes in the AST or symbols in the
// symbol table.
//
// Types without an array size will be given one.
// Types already having a size that is wrong will get an error.
//
void HlslParseContext::checkIoArraysConsistency(const TSourceLoc& loc, bool tailOnly)
{
int requiredSize = getIoArrayImplicitSize();
if (requiredSize == 0)
return;
const char* feature;
if (language == EShLangGeometry)
feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
else if (language == EShLangTessControl)
feature = "vertices";
else
feature = "unknown";
if (tailOnly) {
checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
return;
}
for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
}
int HlslParseContext::getIoArrayImplicitSize() const
{
if (language == EShLangGeometry)
return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
else if (language == EShLangTessControl)
return intermediate.getVertices() != TQualifier::layoutNotSet ? intermediate.getVertices() : 0;
else
return 0;
}
void HlslParseContext::checkIoArrayConsistency(const TSourceLoc& /*loc*/, int requiredSize, const char* /*feature*/, TType& type, const TString& /*name*/)
{
if (type.isImplicitlySizedArray())
type.changeOuterArraySize(requiredSize);
}
// Handle seeing a binary node with a math operation.
TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
{
TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
if (! result)
binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
return result;
}
// Handle seeing a unary node with a math operation.
TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
{
TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
if (result)
return result;
else
unaryOpError(loc, str, childNode->getCompleteString());
return childNode;
}
//
// Handle seeing a base.field dereference in the grammar.
//
TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
{
variableCheck(base);
//
// methods can't be resolved until we later see the function-calling syntax.
// Save away the name in the AST for now. Processing is completed in
// handleLengthMethod(), etc.
//
if (field == "length") {
return intermediate.addMethod(base, TType(EbtInt), &field, loc);
} else if (field == "CalculateLevelOfDetail" ||
field == "CalculateLevelOfDetailUnclamped" ||
field == "Gather" ||
field == "GatherRed" ||
field == "GatherGreen" ||
field == "GatherBlue" ||
field == "GatherAlpha" ||
field == "GatherCmp" ||
field == "GatherCmpRed" ||
field == "GatherCmpGreen" ||
field == "GatherCmpBlue" ||
field == "GatherCmpAlpha" ||
field == "GetDimensions" ||
field == "GetSamplePosition" ||
field == "Load" ||
field == "Sample" ||
field == "SampleBias" ||
field == "SampleCmp" ||
field == "SampleCmpLevelZero" ||
field == "SampleGrad" ||
field == "SampleLevel") {
// If it's not a method on a sampler object, we fall through in case it is a struct member.
if (base->getType().getBasicType() == EbtSampler) {
const TSampler& texType = base->getType().getSampler();
if (! texType.isPureSampler()) {
const int vecSize = texType.isShadow() ? 1 : 4;
return intermediate.addMethod(base, TType(texType.type, EvqTemporary, vecSize), &field, loc);
}
}
}
// It's not .length() if we get to here.
if (base->isArray()) {
error(loc, "cannot apply to an array:", ".", field.c_str());
return base;
}
// It's neither an array nor .length() if we get here,
// leaving swizzles and struct/block dereferences.
TIntermTyped* result = base;
if (base->isVector() || base->isScalar()) {
TVectorFields fields;
if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
fields.num = 1;
fields.offsets[0] = 0;
}
if (base->isScalar()) {
if (fields.num == 1)
return result;
else {
TType type(base->getBasicType(), EvqTemporary, fields.num);
return addConstructor(loc, base, type);
}
}
if (base->getType().getQualifier().isFrontEndConstant())
result = intermediate.foldSwizzle(base, fields, loc);
else {
if (fields.num == 1) {
TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
result->setType(TType(base->getBasicType(), EvqTemporary));
} else {
TString vectorString = field;
TIntermTyped* index = intermediate.addSwizzle(fields, loc);
result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int)vectorString.size()));
}
}
} else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
const TTypeList* fields = base->getType().getStruct();
bool fieldFound = false;
int member;
for (member = 0; member < (int)fields->size(); ++member) {
if ((*fields)[member].type->getFieldName() == field) {
fieldFound = true;
break;
}
}
if (fieldFound) {
if (base->getType().getQualifier().storage == EvqConst)
result = intermediate.foldDereference(base, member, loc);
else {
TIntermTyped* index = intermediate.addConstantUnion(member, loc);
result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
result->setType(*(*fields)[member].type);
}
} else
error(loc, "no such field in structure", field.c_str(), "");
} else
error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
return result;
}
//
// Handle seeing a function declarator in the grammar. This is the precursor
// to recognizing a function prototype or function definition.
//
TFunction* HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
{
//
// Multiple declarations of the same function name are allowed.
//
// If this is a definition, the definition production code will check for redefinitions
// (we don't know at this point if it's a definition or not).
//
bool builtIn;
TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
if (prototype) {
// All built-in functions are defined, even though they don't have a body.
// Count their prototype as a definition instead.
if (symbolTable.atBuiltInLevel())
function.setDefined();
else {
if (prevDec && ! builtIn)
symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
function.setPrototyped();
}
}
// This insert won't actually insert it if it's a duplicate signature, but it will still check for
// other forms of name collisions.
if (! symbolTable.insert(function))
error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
//
// If this is a redeclaration, it could also be a definition,
// in which case, we need to use the parameter names from this one, and not the one that's
// being redeclared. So, pass back this declaration, not the one in the symbol table.
//
return &function;
}
//
// Handle seeing the function prototype in front of a function definition in the grammar.
// The body is handled after this function returns.
//
TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
{
currentCaller = function.getMangledName();
TSymbol* symbol = symbolTable.find(function.getMangledName());
TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
if (! prevDec)
error(loc, "can't find function", function.getName().c_str(), "");
// Note: 'prevDec' could be 'function' if this is the first time we've seen function
// as it would have just been put in the symbol table. Otherwise, we're looking up
// an earlier occurrence.
if (prevDec && prevDec->isDefined()) {
// Then this function already has a body.
error(loc, "function already has a body", function.getName().c_str(), "");
}
if (prevDec && ! prevDec->isDefined()) {
prevDec->setDefined();
// Remember the return type for later checking for RETURN statements.
currentFunctionType = &(prevDec->getType());
} else
currentFunctionType = new TType(EbtVoid);
functionReturnsValue = false;
inEntrypoint = (function.getName() == intermediate.getEntryPoint().c_str());
if (inEntrypoint) {
// parameters are actually shader-level inputs
for (int i = 0; i < function.getParamCount(); i++)
function[i].type->getQualifier().storage = EvqVaryingIn;
}
//
// New symbol table scope for body of function plus its arguments
//
pushScope();
//
// Insert parameters into the symbol table.
// If the parameter has no name, it's not an error, just don't insert it
// (could be used for unused args).
//
// Also, accumulate the list of parameters into the HIL, so lower level code
// knows where to find parameters.
//
TIntermAggregate* paramNodes = new TIntermAggregate;
for (int i = 0; i < function.getParamCount(); i++) {
TParameter& param = function[i];
if (param.name != nullptr) {
TVariable *variable = new TVariable(param.name, *param.type);
// Insert the parameters with name in the symbol table.
if (! symbolTable.insert(*variable))
error(loc, "redefinition", variable->getName().c_str(), "");
else {
// Transfer ownership of name pointer to symbol table.
param.name = nullptr;
// Add the parameter to the HIL
paramNodes = intermediate.growAggregate(paramNodes,
intermediate.addSymbol(*variable, loc),
loc);
}
} else
paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
}
intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
loopNestingLevel = 0;
controlFlowNestingLevel = 0;
postMainReturn = false;
return paramNodes;
}
// Handle function returns, including type conversions to the function return type
// if necessary.
TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
{
if (currentFunctionType->getBasicType() == EbtVoid) {
error(loc, "void function cannot return a value", "return", "");
return intermediate.addBranch(EOpReturn, loc);
} else if (*currentFunctionType != value->getType()) {
TIntermTyped* converted = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
if (converted) {
return intermediate.addBranch(EOpReturn, converted, loc);
} else {
error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
return intermediate.addBranch(EOpReturn, value, loc);
}
} else
return intermediate.addBranch(EOpReturn, value, loc);
}
void HlslParseContext::handleFunctionArgument(TFunction* function, TIntermTyped*& arguments, TIntermTyped* newArg)
{
TParameter param = { 0, new TType };
param.type->shallowCopy(newArg->getType());
function->addParameter(param);
if (arguments)
arguments = intermediate.growAggregate(arguments, newArg);
else
arguments = newArg;
}
//
// HLSL atomic operations have slightly different arguments than
// GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
// This provides the post-decomposition equivalent opcode.
//
TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
{
switch (op) {
case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
case EOpInterlockedCompareStore: // TODO: ...
default:
error(loc, "unknown atomic operation", "unknown op", "");
return EOpNull;
}
}
//
// Create a combined sampler/texture from separate sampler and texture.
//
TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex, TIntermTyped* argSampler)
{
TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
txcombine->getSequence().push_back(argTex);
txcombine->getSequence().push_back(argSampler);
TSampler samplerType = argTex->getType().getSampler();
samplerType.combined = true;
samplerType.shadow = argSampler->getType().getSampler().shadow;
txcombine->setType(TType(samplerType, EvqTemporary));
txcombine->setLoc(loc);
return txcombine;
}
//
// Decompose DX9 and DX10 sample intrinsics & object methods into AST
//
void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
{
if (!node || !node->getAsOperator())
return;
const TOperator op = node->getAsOperator()->getOp();
const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
switch (op) {
// **** DX9 intrinsics: ****
case EOpTexture:
{
// Texture with ddx & ddy is really gradient form in HLSL
if (argAggregate->getSequence().size() == 4) {
node->getAsAggregate()->setOperator(EOpTextureGrad);
break;
}
break;
}
case EOpTextureBias:
{
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
// HLSL puts bias in W component of coordinate. We extract it and add it to
// the argument list, instead
TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
TOperator constructOp = EOpNull;
switch (arg0->getType().getSampler().dim) {
case Esd1D: constructOp = EOpConstructFloat; break; // 1D
case Esd2D: constructOp = EOpConstructVec2; break; // 2D
case Esd3D: constructOp = EOpConstructVec3; break; // 3D
case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
default: break;
}
TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
constructCoord->getSequence().push_back(arg1);
constructCoord->setLoc(loc);
TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
tex->getSequence().push_back(arg0); // sampler
tex->getSequence().push_back(constructCoord); // coordinate
tex->getSequence().push_back(bias); // bias
tex->setLoc(loc);
node = tex;
break;
}
// **** DX10 methods: ****
case EOpMethodSample: // fall through
case EOpMethodSampleBias: // ...
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* argBias = nullptr;
TIntermTyped* argOffset = nullptr;
int nextArg = 3;
if (op == EOpMethodSampleBias) // SampleBias has a bias arg
argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
TOperator textureOp = EOpTexture;
if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
textureOp = EOpTextureOffset;
argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
}
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
TIntermAggregate* txsample = new TIntermAggregate(textureOp);
txsample->getSequence().push_back(txcombine);
txsample->getSequence().push_back(argCoord);
if (argBias != nullptr)
txsample->getSequence().push_back(argBias);
if (argOffset != nullptr)
txsample->getSequence().push_back(argOffset);
txsample->setType(node->getType());
txsample->setLoc(loc);
node = txsample;
break;
}
case EOpMethodSampleGrad: // ...
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
TIntermTyped* argOffset = nullptr;
TOperator textureOp = EOpTextureGrad;
if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
textureOp = EOpTextureGradOffset;
argOffset = argAggregate->getSequence()[5]->getAsTyped();
}
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
TIntermAggregate* txsample = new TIntermAggregate(textureOp);
txsample->getSequence().push_back(txcombine);
txsample->getSequence().push_back(argCoord);
txsample->getSequence().push_back(argDDX);
txsample->getSequence().push_back(argDDY);
if (argOffset != nullptr)
txsample->getSequence().push_back(argOffset);
txsample->setType(node->getType());
txsample->setLoc(loc);
node = txsample;
break;
}
case EOpMethodGetDimensions:
{
// AST returns a vector of results, which we break apart component-wise into
// separate values to assign to the HLSL method's outputs, ala:
// tx . GetDimensions(width, height);
// float2 sizeQueryTemp = EOpTextureQuerySize
// width = sizeQueryTemp.X;
// height = sizeQueryTemp.Y;
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
const TType& texType = argTex->getType();
assert(texType.getBasicType() == EbtSampler);
const TSampler& texSampler = texType.getSampler();
const TSamplerDim dim = texSampler.dim;
const int numArgs = (int)argAggregate->getSequence().size();
int numDims = 0;
switch (dim) {
case Esd1D: numDims = 1; break; // W
case Esd2D: numDims = 2; break; // W, H
case Esd3D: numDims = 3; break; // W, H, D
case EsdCube: numDims = 2; break; // W, H (cube)
default:
assert(0 && "unhandled texture dimension");
}
// Arrayed adds another dimension for the number of array elements
if (texSampler.isArrayed())
++numDims;
// Establish whether we're querying mip levels
const bool mipQuery = (numArgs > (numDims + 1)) && (!texSampler.isMultiSample());
// AST assumes integer return. Will be converted to float if required.
TIntermAggregate* sizeQuery = new TIntermAggregate(EOpTextureQuerySize);
sizeQuery->getSequence().push_back(argTex);
// If we're querying an explicit LOD, add the LOD, which is always arg #1
if (mipQuery) {
TIntermTyped* queryLod = argAggregate->getSequence()[1]->getAsTyped();
sizeQuery->getSequence().push_back(queryLod);
}
sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
sizeQuery->setLoc(loc);
// Return value from size query
TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
tempArg->getWritableType().getQualifier().makeTemporary();
TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign, sizeQueryReturn, sizeQuery, loc);
// Compound statement for assigning outputs
TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
// Index of first output parameter
const int outParamBase = mipQuery ? 2 : 1;
for (int compNum = 0; compNum < numDims; ++compNum) {
TIntermTyped* indexedOut = nullptr;
if (numDims > 1) {
TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
indexedOut->setLoc(loc);
} else {
indexedOut = sizeQueryReturn;
}
TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
}
// handle mip level parameter
if (mipQuery) {
TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
levelsQuery->getSequence().push_back(argTex);
levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
levelsQuery->setLoc(loc);
TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
}
// 2DMS formats query # samples, which needs a different query op
if (texSampler.isMultiSample()) {
TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
samplesQuery->getSequence().push_back(argTex);
samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
samplesQuery->setLoc(loc);
TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
}
compoundStatement->setOperator(EOpSequence);
compoundStatement->setLoc(loc);
compoundStatement->setType(TType(EbtVoid));
node = compoundStatement;
break;
}
case EOpMethodSampleCmp: // fall through...
case EOpMethodSampleCmpLevelZero:
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
TIntermTyped* argOffset = nullptr;
// optional offset value
if (argAggregate->getSequence().size() > 4)
argOffset = argAggregate->getSequence()[4]->getAsTyped();
const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
// AST wants comparison value as one of the texture coordinates
TOperator constructOp = EOpNull;
switch (coordDimWithCmpVal) {
// 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
case 2: constructOp = EOpConstructVec2; break;
case 3: constructOp = EOpConstructVec3; break;
case 4: constructOp = EOpConstructVec4; break;
case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
default: assert(0); break;
}
TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
coordWithCmp->getSequence().push_back(argCoord);
if (coordDimWithCmpVal != 5) // cube array shadow is special.
coordWithCmp->getSequence().push_back(argCmpVal);
coordWithCmp->setLoc(loc);
TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
if (argOffset != nullptr)
textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
// Create combined sampler & texture op
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
TIntermAggregate* txsample = new TIntermAggregate(textureOp);
txsample->getSequence().push_back(txcombine);
txsample->getSequence().push_back(coordWithCmp);
if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
txsample->getSequence().push_back(argCmpVal);
// the LevelZero form uses 0 as an explicit LOD
if (op == EOpMethodSampleCmpLevelZero)
txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
// Add offset if present
if (argOffset != nullptr)
txsample->getSequence().push_back(argOffset);
txsample->setType(node->getType());
txsample->setLoc(loc);
node = txsample;
break;
}
case EOpMethodLoad:
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argOffset = nullptr;
TIntermTyped* lodComponent = nullptr;
TIntermTyped* coordSwizzle = nullptr;
const bool isMS = argTex->getType().getSampler().isMultiSample();
const bool isBuffer = argTex->getType().getSampler().dim == EsdBuffer;
const TBasicType coordBaseType = argCoord->getType().getBasicType();
// Last component of coordinate is the mip level, for non-MS. we separate them here:
if (isMS || isBuffer) {
// MS and Buffer have no LOD
coordSwizzle = argCoord;
} else {
// Extract coordinate
TVectorFields coordFields(0,1,2,3);
coordFields.num = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.num));
// Extract LOD
TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.num, loc, true);
lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
}
const int numArgs = (int)argAggregate->getSequence().size();
const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
// Create texel fetch
const TOperator fetchOp = (hasOffset ? EOpTextureFetchOffset : EOpTextureFetch);
TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
// Build up the fetch
txfetch->getSequence().push_back(argTex);
txfetch->getSequence().push_back(coordSwizzle);
if (isMS) {
// add 2DMS sample index
TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
txfetch->getSequence().push_back(argSampleIdx);
} else if (isBuffer) {
// Nothing else to do for buffers.
} else {
// 2DMS and buffer have no LOD, but everything else does.
txfetch->getSequence().push_back(lodComponent);
}
// Obtain offset arg, if there is one.
if (hasOffset) {
const int offsetPos = (isMS ? 3 : 2);
argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
txfetch->getSequence().push_back(argOffset);
}
txfetch->setType(node->getType());
txfetch->setLoc(loc);
node = txfetch;
break;
}
case EOpMethodSampleLevel:
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
TIntermTyped* argOffset = nullptr;
const int numArgs = (int)argAggregate->getSequence().size();
if (numArgs == 5) // offset, if present
argOffset = argAggregate->getSequence()[4]->getAsTyped();
const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
TIntermAggregate* txsample = new TIntermAggregate(textureOp);
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
txsample->getSequence().push_back(txcombine);
txsample->getSequence().push_back(argCoord);
txsample->getSequence().push_back(argLod);
if (argOffset != nullptr)
txsample->getSequence().push_back(argOffset);
txsample->setType(node->getType());
txsample->setLoc(loc);
node = txsample;
break;
}
case EOpMethodGather:
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* argOffset = nullptr;
// Offset is optional
if (argAggregate->getSequence().size() > 3)
argOffset = argAggregate->getSequence()[3]->getAsTyped();
const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
TIntermAggregate* txgather = new TIntermAggregate(textureOp);
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
txgather->getSequence().push_back(txcombine);
txgather->getSequence().push_back(argCoord);
// Offset if not given is implicitly channel 0 (red)
if (argOffset != nullptr)
txgather->getSequence().push_back(argOffset);
txgather->setType(node->getType());
txgather->setLoc(loc);
node = txgather;
break;
}
case EOpMethodGatherRed: // fall through...
case EOpMethodGatherGreen: // ...
case EOpMethodGatherBlue: // ...
case EOpMethodGatherAlpha: // ...
case EOpMethodGatherCmpRed: // ...
case EOpMethodGatherCmpGreen: // ...
case EOpMethodGatherCmpBlue: // ...
case EOpMethodGatherCmpAlpha: // ...
{
int channel = 0; // the channel we are gathering
int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
switch (op) {
case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
case EOpMethodGatherRed: channel = 0; break;
case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
case EOpMethodGatherGreen: channel = 1; break;
case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
case EOpMethodGatherBlue: channel = 2; break;
case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
case EOpMethodGatherAlpha: channel = 3; break;
default: assert(0); break;
}
// For now, we have nothing to map the component-wise comparison forms
// to, because neither GLSL nor SPIR-V has such an opcode. Issue an
// unimplemented error instead. Most of the machinery is here if that
// should ever become available.
if (cmpValues) {
error(loc, "unimplemented: component-level gather compare", "", "");
return;
}
int arg = 0;
TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
TIntermTyped* argOffset = nullptr;
TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
// TIntermTyped* argStatus = nullptr; // TODO: residency
TIntermTyped* argCmp = nullptr;
const TSamplerDim dim = argTex->getType().getSampler().dim;
const int argSize = (int)argAggregate->getSequence().size();
bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
bool hasOffset1 = false;
bool hasOffset4 = false;
// Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
if (dim == Esd2D) {
hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
}
assert(!(hasOffset1 && hasOffset4));
TOperator textureOp = EOpTextureGather;
// Compare forms have compare value
if (cmpValues != 0)
argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
// Some forms have single offset
if (hasOffset1) {
textureOp = EOpTextureGatherOffset; // single offset form
argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
}
// Some forms have 4 gather offsets
if (hasOffset4) {
textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
}
// Residency status
if (hasStatus) {
// argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
error(loc, "unimplemented: residency status", "", "");
return;
}
TIntermAggregate* txgather = new TIntermAggregate(textureOp);
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
txgather->getSequence().push_back(txcombine);
txgather->getSequence().push_back(argCoord);
// AST wants an array of 4 offsets, where HLSL has separate args. Here
// we construct an array from the separate args.
if (hasOffset4) {
TType arrayType(EbtInt, EvqTemporary, 2);
TArraySizes arraySizes;
arraySizes.addInnerSize(4);
arrayType.newArraySizes(arraySizes);
TIntermAggregate* initList = new TIntermAggregate(EOpNull);
for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
initList->getSequence().push_back(argOffsets[offsetNum]);
argOffset = addConstructor(loc, initList, arrayType);
}
// Add comparison value if we have one
if (argTex->getType().getSampler().isShadow())
txgather->getSequence().push_back(argCmp);
// Add offset (either 1, or an array of 4) if we have one
if (argOffset != nullptr)
txgather->getSequence().push_back(argOffset);
txgather->getSequence().push_back(argChannel);
txgather->setType(node->getType());
txgather->setLoc(loc);
node = txgather;
break;
}
case EOpMethodCalculateLevelOfDetail:
case EOpMethodCalculateLevelOfDetailUnclamped:
{
TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
txquerylod->getSequence().push_back(txcombine);
txquerylod->getSequence().push_back(argCoord);
TIntermTyped* lodComponent = intermediate.addConstantUnion(0, loc, true);
TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
node = lodComponentIdx;
// We cannot currently obtain the unclamped LOD
if (op == EOpMethodCalculateLevelOfDetailUnclamped)
error(loc, "unimplemented: CalculateLevelOfDetailUnclamped", "", "");
break;
}
case EOpMethodGetSamplePosition:
{
error(loc, "unimplemented: GetSamplePosition", "", "");
break;
}
default:
break; // most pass through unchanged
}
}
//
// Optionally decompose intrinsics to AST opcodes.
//
void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
{
// HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
// opcodes for compatibility with existing software stacks.
static const bool decomposeHlslIntrinsics = true;
if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
return;
const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
TIntermUnary* fnUnary = node->getAsUnaryNode();
const TOperator op = node->getAsOperator()->getOp();
switch (op) {
case EOpGenMul:
{
// mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
if (arg0->isVector() && arg1->isVector()) { // vec * vec
node->getAsAggregate()->setOperator(EOpDot);
} else {
node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
}
break;
}
case EOpRcp:
{
// rcp(a) -> 1 / a
TIntermTyped* arg0 = fnUnary->getOperand();
TBasicType type0 = arg0->getBasicType();
TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
break;
}
case EOpSaturate:
{
// saturate(a) -> clamp(a,0,1)
TIntermTyped* arg0 = fnUnary->getOperand();
TBasicType type0 = arg0->getBasicType();
TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
clamp->getSequence().push_back(arg0);
clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
clamp->setLoc(loc);
clamp->setType(node->getType());
clamp->getWritableType().getQualifier().makeTemporary();
node = clamp;
break;
}
case EOpSinCos:
{
// sincos(a,b,c) -> b = sin(a), c = cos(a)
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
compoundStatement->setOperator(EOpSequence);
compoundStatement->setLoc(loc);
compoundStatement->setType(TType(EbtVoid));
node = compoundStatement;
break;
}
case EOpClip:
{
// clip(a) -> if (any(a<0)) discard;
TIntermTyped* arg0 = fnUnary->getOperand();
TBasicType type0 = arg0->getBasicType();
TIntermTyped* compareNode = nullptr;
// For non-scalars: per experiment with FXC compiler, discard if any component < 0.
if (!arg0->isScalar()) {
// component-wise compare: a < 0
TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
less->getSequence().push_back(arg0);
less->setLoc(loc);
// make vec or mat of bool matching dimensions of input
less->setType(TType(EbtBool, EvqTemporary,
arg0->getType().getVectorSize(),
arg0->getType().getMatrixCols(),
arg0->getType().getMatrixRows(),
arg0->getType().isVector()));
// calculate # of components for comparison const
const int constComponentCount =
std::max(arg0->getType().getVectorSize(), 1) *
std::max(arg0->getType().getMatrixCols(), 1) *
std::max(arg0->getType().getMatrixRows(), 1);
TConstUnion zero;
zero.setDConst(0.0);
TConstUnionArray zeros(constComponentCount, zero);
less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
} else {
TIntermTyped* zero = intermediate.addConstantUnion(0, type0, loc, true);
compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
}
TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
node = new TIntermSelection(compareNode, killNode, nullptr);
node->setLoc(loc);
break;
}
case EOpLog10:
{
// log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
TIntermTyped* arg0 = fnUnary->getOperand();
TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
break;
}
case EOpDst:
{
// dest.x = 1;
// dest.y = src0.y * src1.y;
// dest.z = src0.z;
// dest.w = src1.w;
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
dst->getSequence().push_back(src0z);
dst->getSequence().push_back(src1w);
dst->setType(TType(EbtFloat, EvqTemporary, 4));
dst->setLoc(loc);
node = dst;
break;
}
case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
case EOpInterlockedMin: // ...
case EOpInterlockedMax: // ...
case EOpInterlockedAnd: // ...
case EOpInterlockedOr: // ...
case EOpInterlockedXor: // ...
case EOpInterlockedExchange: // always has output arg
{
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
const bool isImage = arg0->getType().isImage();
const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
if (argAggregate->getSequence().size() > 2) {
// optional output param is present. return value goes to arg2.
TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
atomic->getSequence().push_back(arg0);
atomic->getSequence().push_back(arg1);
atomic->setLoc(loc);
atomic->setType(arg0->getType());
atomic->getWritableType().getQualifier().makeTemporary();
node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
} else {
// Set the matching operator. Since output is absent, this is all we need to do.
node->getAsAggregate()->setOperator(atomicOp);
}
break;
}
case EOpInterlockedCompareExchange:
{
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
const bool isImage = arg0->getType().isImage();
TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
atomic->getSequence().push_back(arg0);
atomic->getSequence().push_back(arg1);
atomic->getSequence().push_back(arg2);
atomic->setLoc(loc);
atomic->setType(arg2->getType());
atomic->getWritableType().getQualifier().makeTemporary();
node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
break;
}
case EOpEvaluateAttributeSnapped:
{
// SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
// HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
// iU = (iU<<28)>>28
// fU = ((float)iU)/16
// Targets might handle this natively, in which case they can disable
// decompositions.
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
i28);
TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
intermediate.addConversion(EOpConstructFloat,
TType(EbtFloat, EvqTemporary, 2), iU),
recip16);
TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
interp->getSequence().push_back(arg0);
interp->getSequence().push_back(floatOffset);
interp->setLoc(loc);
interp->setType(arg0->getType());
interp->getWritableType().getQualifier().makeTemporary();
node = interp;
break;
}
case EOpLit:
{
TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
// Ambient
dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
// Diffuse:
TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
diffuse->getSequence().push_back(n_dot_l);
diffuse->getSequence().push_back(zero);
diffuse->setLoc(loc);
diffuse->setType(TType(EbtFloat));
dst->getSequence().push_back(diffuse);
// Specular:
TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
min_ndot->getSequence().push_back(n_dot_l);
min_ndot->getSequence().push_back(n_dot_h);
min_ndot->setLoc(loc);
min_ndot->setType(TType(EbtFloat));
TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
// One:
dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
dst->setLoc(loc);
dst->setType(TType(EbtFloat, EvqTemporary, 4));
node = dst;
break;
}
case EOpAsDouble:
{
// asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
// first construct a uint64.
TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
if (arg0->getType().isVector()) { // TODO: ...
error(loc, "double2 conversion not implemented", "asdouble", "");
break;
}
TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
uint64->getSequence().push_back(arg0);
uint64->getSequence().push_back(arg1);
uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
uint64->setLoc(loc);
// bitcast uint2 to a double
TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
convert->getAsUnaryNode()->setOperand(uint64);
convert->setLoc(loc);
convert->setType(TType(EbtDouble, EvqTemporary));
node = convert;
break;
}
case EOpF16tof32:
case EOpF32tof16:
{
// Temporary until decomposition is available.
error(loc, "unimplemented intrinsic: handle natively", "f32tof16", "");
break;
}
default:
break; // most pass through unchanged
}
}
//
// Handle seeing function call syntax in the grammar, which could be any of
// - .length() method
// - constructor
// - a call to a built-in function mapped to an operator
// - a call to a built-in function that will remain a function call (e.g., texturing)
// - user function
// - subroutine call (not implemented yet)
//
TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
{
TIntermTyped* result = nullptr;
TOperator op = function->getBuiltInOp();
if (op == EOpArrayLength)
result = handleLengthMethod(loc, function, arguments);
else if (op != EOpNull) {
//
// Then this should be a constructor.
// Don't go through the symbol table for constructors.
// Their parameters will be verified algorithmically.
//
TType type(EbtVoid); // use this to get the type back
if (! constructorError(loc, arguments, *function, op, type)) {
//
// It's a constructor, of type 'type'.
//
result = addConstructor(loc, arguments, type);
if (result == nullptr)
error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
}
} else {
//
// Find it in the symbol table.
//
const TFunction* fnCandidate;
bool builtIn;
fnCandidate = findFunction(loc, *function, builtIn);
if (fnCandidate) {
// This is a declared function that might map to
// - a built-in operator,
// - a built-in function not mapped to an operator, or
// - a user function.
// Error check for a function requiring specific extensions present.
if (builtIn && fnCandidate->getNumExtensions())
requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
if (arguments) {
// Make sure qualifications work for these arguments.
//TIntermAggregate* aggregate = arguments->getAsAggregate();
//for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
// // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
// // is the single argument itself or its children are the arguments. Only one argument
// // means take 'arguments' itself as the one argument.
// TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
// TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
// TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
//}
// Convert 'in' arguments
addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
}
op = fnCandidate->getBuiltInOp();
if (builtIn && op != EOpNull) {
// A function call mapped to a built-in operation.
result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
if (result == nullptr) {
error(arguments->getLoc(), " wrong operand type", "Internal Error",
"built in unary operator function. Type: %s",
static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
} else if (result->getAsOperator()) {
builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
}
} else {
// This is a function call not mapped to built-in operator.
// It could still be a built-in function, but only if PureOperatorBuiltins == false.
result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
TIntermAggregate* call = result->getAsAggregate();
call->setName(fnCandidate->getMangledName());
// this is how we know whether the given function is a built-in function or a user-defined function
// if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
// if builtIn == true, it's definitely a built-in function with EOpNull
if (! builtIn) {
call->setUserDefined();
intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
}
}
// Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
// Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
// Also, build the qualifier list for user function calls, which are always called with an aggregate.
if (result->getAsAggregate()) {
TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
qualifierList.push_back(qual);
}
result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
}
decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
}
}
// generic error recovery
// TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
if (result == nullptr)
result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
return result;
}
// Finish processing object.length(). This started earlier in handleDotDereference(), where
// the ".length" part was recognized and semantically checked, and finished here where the
// function syntax "()" is recognized.
//
// Return resulting tree node.
TIntermTyped* HlslParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
{
int length = 0;
if (function->getParamCount() > 0)
error(loc, "method does not accept any arguments", function->getName().c_str(), "");
else {
const TType& type = intermNode->getAsTyped()->getType();
if (type.isArray()) {
if (type.isRuntimeSizedArray()) {
// Create a unary op and let the back end handle it
return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
} else if (type.isImplicitlySizedArray()) {
if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
// We could be between a layout declaration that gives a built-in io array implicit size and
// a user redeclaration of that array, meaning we have to substitute its implicit size here
// without actually redeclaring the array. (It is an error to use a member before the
// redeclaration, but not an error to use the array name itself.)
const TString& name = intermNode->getAsSymbolNode()->getName();
if (name == "gl_in" || name == "gl_out")
length = getIoArrayImplicitSize();
}
if (length == 0) {
if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
else
error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
}
} else
length = type.getOuterArraySize();
} else if (type.isMatrix())
length = type.getMatrixCols();
else if (type.isVector())
length = type.getVectorSize();
else {
// we should not get here, because earlier semantic checking should have prevented this path
error(loc, ".length()", "unexpected use of .length()", "");
}
}
if (length == 0)
length = 1;
return intermediate.addConstantUnion(length, loc);
}
//
// Add any needed implicit conversions for function-call arguments to input parameters.
//
void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
{
TIntermAggregate* aggregate = arguments->getAsAggregate();
// Process each argument's conversion
for (int i = 0; i < function.getParamCount(); ++i) {
// At this early point there is a slight ambiguity between whether an aggregate 'arguments'
// is the single argument itself or its children are the arguments. Only one argument
// means take 'arguments' itself as the one argument.
TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
if (*function[i].type != arg->getType()) {
if (function[i].type->getQualifier().isParamInput()) {
// In-qualified arguments just need an extra node added above the argument to
// convert to the correct type.
arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
if (arg) {
if (function.getParamCount() == 1)
arguments = arg;
else {
if (aggregate)
aggregate->getSequence()[i] = arg;
else
arguments = arg;
}
}
}
}
}
}
//
// Add any needed implicit output conversions for function-call arguments. This
// can require a new tree topology, complicated further by whether the function
// has a return value.
//
// Returns a node of a subtree that evaluates to the return value of the function.
//
TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
{
TIntermSequence& arguments = intermNode.getSequence();
// Will there be any output conversions?
bool outputConversions = false;
for (int i = 0; i < function.getParamCount(); ++i) {
if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
outputConversions = true;
break;
}
}
if (! outputConversions)
return &intermNode;
// Setup for the new tree, if needed:
//
// Output conversions need a different tree topology.
// Out-qualified arguments need a temporary of the correct type, with the call
// followed by an assignment of the temporary to the original argument:
// void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
// ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
// Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
TIntermTyped* conversionTree = nullptr;
TVariable* tempRet = nullptr;
if (intermNode.getBasicType() != EbtVoid) {
// do the "tempRet = function(...), " bit from above
tempRet = makeInternalVariable("tempReturn", intermNode.getType());
TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
} else
conversionTree = &intermNode;
conversionTree = intermediate.makeAggregate(conversionTree);
// Process each argument's conversion
for (int i = 0; i < function.getParamCount(); ++i) {
if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
if (function[i].type->getQualifier().isParamOutput()) {
// Out-qualified arguments need to use the topology set up above.
// do the " ...(tempArg, ...), arg = tempArg" bit from above
TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
tempArg->getWritableType().getQualifier().makeTemporary();
TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
// replace the argument with another node for the same tempArg variable
arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
}
}
}
// Finalize the tree topology (see bigger comment above).
if (tempRet) {
// do the "..., tempRet" bit from above
TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
}
conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
return conversionTree;
}
//
// Do additional checking of built-in function calls that is not caught
// by normal semantic checks on argument type, extension tagging, etc.
//
// Assumes there has been a semantically correct match to a built-in function prototype.
//
void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
{
// Set up convenience accessors to the argument(s). There is almost always
// multiple arguments for the cases below, but when there might be one,
// check the unaryArg first.
const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
const TIntermTyped* unaryArg = nullptr;
const TIntermTyped* arg0 = nullptr;
if (callNode.getAsAggregate()) {
argp = &callNode.getAsAggregate()->getSequence();
if (argp->size() > 0)
arg0 = (*argp)[0]->getAsTyped();
} else {
assert(callNode.getAsUnaryNode());
unaryArg = callNode.getAsUnaryNode()->getOperand();
arg0 = unaryArg;
}
const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
switch (callNode.getOp()) {
case EOpTextureGather:
case EOpTextureGatherOffset:
case EOpTextureGatherOffsets:
{
// Figure out which variants are allowed by what extensions,
// and what arguments must be constant for which situations.
TString featureString = fnCandidate.getName() + "(...)";
const char* feature = featureString.c_str();
int compArg = -1; // track which argument, if any, is the constant component argument
switch (callNode.getOp()) {
case EOpTextureGather:
// More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
// otherwise, need GL_ARB_texture_gather.
if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 2;
}
break;
case EOpTextureGatherOffset:
// GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 3;
break;
case EOpTextureGatherOffsets:
if (! fnCandidate[0].type->getSampler().shadow)
compArg = 3;
break;
default:
break;
}
if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
if (aggArgs[compArg]->getAsConstantUnion()) {
int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
if (value < 0 || value > 3)
error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
} else
error(loc, "must be a compile-time constant:", feature, "component argument");
}
break;
}
case EOpTextureOffset:
case EOpTextureFetchOffset:
case EOpTextureProjOffset:
case EOpTextureLodOffset:
case EOpTextureProjLodOffset:
case EOpTextureGradOffset:
case EOpTextureProjGradOffset:
{
// Handle texture-offset limits checking
// Pick which argument has to hold constant offsets
int arg = -1;
switch (callNode.getOp()) {
case EOpTextureOffset: arg = 2; break;
case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
case EOpTextureProjOffset: arg = 2; break;
case EOpTextureLodOffset: arg = 3; break;
case EOpTextureProjLodOffset: arg = 3; break;
case EOpTextureGradOffset: arg = 4; break;
case EOpTextureProjGradOffset: arg = 4; break;
default:
assert(0);
break;
}
if (arg > 0) {
if (! aggArgs[arg]->getAsConstantUnion())
error(loc, "argument must be compile-time constant", "texel offset", "");
else {
const TType& type = aggArgs[arg]->getAsTyped()->getType();
for (int c = 0; c < type.getVectorSize(); ++c) {
int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
}
}
}
break;
}
case EOpTextureQuerySamples:
case EOpImageQuerySamples:
break;
case EOpImageAtomicAdd:
case EOpImageAtomicMin:
case EOpImageAtomicMax:
case EOpImageAtomicAnd:
case EOpImageAtomicOr:
case EOpImageAtomicXor:
case EOpImageAtomicExchange:
case EOpImageAtomicCompSwap:
break;
case EOpInterpolateAtCentroid:
case EOpInterpolateAtSample:
case EOpInterpolateAtOffset:
// Make sure the first argument is an interpolant, or an array element of an interpolant
if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
// It might still be an array element.
//
// We could check more, but the semantics of the first argument are already met; the
// only way to turn an array into a float/vec* is array dereference and swizzle.
//
// ES and desktop 4.3 and earlier: swizzles may not be used
// desktop 4.4 and later: swizzles may be used
const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
}
break;
default:
break;
}
}
//
// Handle seeing a built-in constructor in a grammar production.
//
TFunction* HlslParseContext::handleConstructorCall(const TSourceLoc& loc, const TType& type)
{
TOperator op = intermediate.mapTypeToConstructorOp(type);
if (op == EOpNull) {
error(loc, "cannot construct this type", type.getBasicString(), "");
return nullptr;
}
TString empty("");
return new TFunction(&empty, type, op);
}
//
// Handle seeing a "COLON semantic" at the end of a type declaration,
// by updating the type according to the semantic.
//
void HlslParseContext::handleSemantic(TType& type, const TString& semantic)
{
// TODO: need to know if it's an input or an output
// The following sketches what needs to be done, but can't be right
// without taking into account stage and input/output.
if (semantic == "PSIZE")
type.getQualifier().builtIn = EbvPointSize;
else if (semantic == "POSITION")
type.getQualifier().builtIn = EbvPosition;
else if (semantic == "FOG")
type.getQualifier().builtIn = EbvFogFragCoord;
else if (semantic == "DEPTH" || semantic == "SV_Depth")
type.getQualifier().builtIn = EbvFragDepth;
else if (semantic == "VFACE" || semantic == "SV_IsFrontFace")
type.getQualifier().builtIn = EbvFace;
else if (semantic == "VPOS" || semantic == "SV_Position")
type.getQualifier().builtIn = EbvFragCoord;
else if (semantic == "SV_ClipDistance")
type.getQualifier().builtIn = EbvClipDistance;
else if (semantic == "SV_CullDistance")
type.getQualifier().builtIn = EbvCullDistance;
else if (semantic == "SV_VertexID")
type.getQualifier().builtIn = EbvVertexId;
else if (semantic == "SV_ViewportArrayIndex")
type.getQualifier().builtIn = EbvViewportIndex;
}
//
// Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
//
// 'location' has the "c[Subcomponent]" part.
// 'component' points to the "component" part, or nullptr if not present.
//
void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TType& type, const glslang::TString& location,
const glslang::TString* component)
{
if (location.size() == 0 || location[0] != 'c') {
error(loc, "expected 'c'", "packoffset", "");
return;
}
if (location.size() == 1)
return;
if (! isdigit(location[1])) {
error(loc, "expected number after 'c'", "packoffset", "");
return;
}
type.getQualifier().layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
if (component != nullptr) {
int componentOffset = 0;
switch ((*component)[0]) {
case 'x': componentOffset = 0; break;
case 'y': componentOffset = 4; break;
case 'z': componentOffset = 8; break;
case 'w': componentOffset = 12; break;
default:
componentOffset = -1;
break;
}
if (componentOffset < 0 || component->size() > 1) {
error(loc, "expected {x, y, z, w} for component", "packoffset", "");
return;
}
type.getQualifier().layoutOffset += componentOffset;
}
}
//
// Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
//
// 'profile' points to the shader_profile part, or nullptr if not present.
// 'desc' is the type# part.
//
void HlslParseContext::handleRegister(const TSourceLoc& loc, TType& type, const glslang::TString* profile,
const glslang::TString& desc,
int subComponent)
{
if (profile != nullptr)
warn(loc, "ignoring shader_profile", "register", "");
if (desc.size() < 1) {
error(loc, "expected register type", "register", "");
return;
}
int regNumber = 0;
if (desc.size() > 1) {
if (isdigit(desc[1]))
regNumber = atoi(desc.substr(1, desc.size()).c_str());
else {
error(loc, "expected register number after register type", "register", "");
return;
}
}
// TODO: learn what all these really mean and how they interact with regNumber and subComponent
switch (desc[0]) {
case 'b':
case 't':
case 'c':
case 's':
type.getQualifier().layoutBinding = regNumber + subComponent;
break;
default:
warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
break;
}
}
//
// Same error message for all places assignments don't work.
//
void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
{
error(loc, "", op, "cannot convert from '%s' to '%s'",
right.c_str(), left.c_str());
}
//
// Same error message for all places unary operations don't work.
//
void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
{
error(loc, " wrong operand type", op,
"no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
op, operand.c_str());
}
//
// Same error message for all binary operations don't work.
//
void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
{
error(loc, " wrong operand types:", op,
"no operation '%s' exists that takes a left-hand operand of type '%s' and "
"a right operand of type '%s' (or there is no acceptable conversion)",
op, left.c_str(), right.c_str());
}
//
// A basic type of EbtVoid is a key that the name string was seen in the source, but
// it was not found as a variable in the symbol table. If so, give the error
// message and insert a dummy variable in the symbol table to prevent future errors.
//
void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
{
TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
if (! symbol)
return;
if (symbol->getType().getBasicType() == EbtVoid) {
error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
// Add to symbol table to prevent future error messages on the same name
if (symbol->getName().size() > 0) {
TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
symbolTable.insert(*fakeVariable);
// substitute a symbol node for this new variable
nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
}
}
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// a constant.
//
void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
{
if (node->getQualifier().storage != EvqConst)
error(node->getLoc(), "constant expression required", token, "");
}
//
// Both test, and if necessary spit out an error, to see if the node is really
// an integer.
//
void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
{
if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
return;
error(node->getLoc(), "scalar integer expression required", token, "");
}
//
// Both test, and if necessary spit out an error, to see if we are currently
// globally scoped.
//
void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
{
if (! symbolTable.atGlobalLevel())