blob: 1ba7d08af2a4e32ef13d8335dc9f014c331422d6 [file] [log] [blame]
John Kesseniche01a9bc2016-03-12 20:11:22 -07001//
2//Copyright (C) 2016 Google, Inc.
LoopDawg592860c2016-06-09 08:57:35 -06003//Copyright (C) 2016 LunarG, Inc.
John Kesseniche01a9bc2016-03-12 20:11:22 -07004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35//
36
37#include "hlslParseHelper.h"
38#include "hlslScanContext.h"
39#include "hlslGrammar.h"
40
41#include "../glslang/MachineIndependent/Scan.h"
42#include "../glslang/MachineIndependent/preprocessor/PpContext.h"
43
44#include "../glslang/OSDependent/osinclude.h"
45
John Kesseniche01a9bc2016-03-12 20:11:22 -070046#include <algorithm>
47
48namespace glslang {
49
50HlslParseContext::HlslParseContext(TSymbolTable& symbolTable, TIntermediate& interm, bool /*parsingBuiltins*/,
John Kessenichb901ade2016-06-16 20:59:42 -060051 int version, EProfile profile, const SpvVersion& spvVersion, EShLanguage language, TInfoSink& infoSink,
John Kesseniche01a9bc2016-03-12 20:11:22 -070052 bool forwardCompatible, EShMessages messages) :
John Kessenichb901ade2016-06-16 20:59:42 -060053 TParseContextBase(symbolTable, interm, version, profile, spvVersion, language, infoSink, forwardCompatible, messages),
John Kessenicha1e2d492016-09-20 13:22:58 -060054 contextPragma(true, false),
55 loopNestingLevel(0), annotationNestingLevel(0), structNestingLevel(0), controlFlowNestingLevel(0),
John Kesseniche01a9bc2016-03-12 20:11:22 -070056 postMainReturn(false),
57 limits(resources.limits),
John Kessenich7dc630f2016-09-16 01:44:43 -060058 entryPointOutput(nullptr),
59 nextInLocation(0), nextOutLocation(0)
John Kesseniche01a9bc2016-03-12 20:11:22 -070060{
61 // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
62 linkage = new TIntermAggregate;
63
64 globalUniformDefaults.clear();
John Kessenich10f7fc72016-09-25 20:25:06 -060065 globalUniformDefaults.layoutMatrix = ElmRowMajor;
John Kessenichb901ade2016-06-16 20:59:42 -060066 globalUniformDefaults.layoutPacking = ElpStd140;
John Kesseniche01a9bc2016-03-12 20:11:22 -070067
68 globalBufferDefaults.clear();
John Kessenich10f7fc72016-09-25 20:25:06 -060069 globalBufferDefaults.layoutMatrix = ElmRowMajor;
John Kessenichb901ade2016-06-16 20:59:42 -060070 globalBufferDefaults.layoutPacking = ElpStd430;
John Kesseniche01a9bc2016-03-12 20:11:22 -070071
72 globalInputDefaults.clear();
73 globalOutputDefaults.clear();
74
75 // "Shaders in the transform
76 // feedback capturing mode have an initial global default of
77 // layout(xfb_buffer = 0) out;"
78 if (language == EShLangVertex ||
79 language == EShLangTessControl ||
80 language == EShLangTessEvaluation ||
81 language == EShLangGeometry)
82 globalOutputDefaults.layoutXfbBuffer = 0;
83
84 if (language == EShLangGeometry)
85 globalOutputDefaults.layoutStream = 0;
John Kessenichd4032292016-09-09 11:43:11 -060086
87 if (spvVersion.spv == 0 || spvVersion.vulkan == 0)
88 infoSink.info << "ERROR: HLSL currently only supported when requesting SPIR-V for Vulkan.\n";
John Kesseniche01a9bc2016-03-12 20:11:22 -070089}
90
91HlslParseContext::~HlslParseContext()
92{
93}
94
LoopDawg62561462016-07-22 20:46:03 -060095void HlslParseContext::initializeExtensionBehavior()
96{
97 TParseContextBase::initializeExtensionBehavior();
98
99 // HLSL allows #line by default.
100 extensionBehavior[E_GL_GOOGLE_cpp_style_line_directive] = EBhEnable;
101}
102
John Kesseniche01a9bc2016-03-12 20:11:22 -0700103void HlslParseContext::setLimits(const TBuiltInResource& r)
104{
105 resources = r;
106 intermediate.setLimits(resources);
107}
108
109//
110// Parse an array of strings using the parser in HlslRules.
111//
112// Returns true for successful acceptance of the shader, false if any errors.
113//
114bool HlslParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
115{
116 currentScanner = &input;
117 ppContext.setInput(input, versionWillBeError);
118
John Kesseniche01a9bc2016-03-12 20:11:22 -0700119 HlslScanContext scanContext(*this, ppContext);
120 HlslGrammar grammar(scanContext, *this);
John Kessenich7f702122016-09-15 22:49:31 -0600121 if (!grammar.parse()) {
John Kessenich219b0252016-08-23 17:51:13 -0600122 // Print a message formated such that if you click on the message it will take you right to
123 // the line through most UIs.
dankbakerafe6e9c2016-08-21 12:29:08 -0400124 const glslang::TSourceLoc& sourceLoc = input.getSourceLoc();
John Kessenich142785f2016-09-19 14:56:55 -0600125 infoSink.info << sourceLoc.name << "(" << sourceLoc.line << "): error at column " << sourceLoc.column << ", HLSL parsing failed.\n";
126 ++numErrors;
John Kessenich7f702122016-09-15 22:49:31 -0600127 return false;
dankbakerafe6e9c2016-08-21 12:29:08 -0400128 }
John Kessenich7f702122016-09-15 22:49:31 -0600129
John Kesseniche01a9bc2016-03-12 20:11:22 -0700130 return numErrors == 0;
131}
132
steve-lunarg07830e82016-10-10 10:00:14 -0600133//
134// Return true if this l-value node should be converted in some manner.
135// For instance: turning a load aggregate into a store in an l-value.
136//
steve-lunarg90707962016-10-07 19:35:40 -0600137bool HlslParseContext::shouldConvertLValue(const TIntermNode* node) const
138{
139 if (node == nullptr)
140 return false;
141
142 const TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
steve-lunarg0de16da2016-10-08 10:54:52 -0600143
steve-lunarg90707962016-10-07 19:35:40 -0600144 if (lhsAsAggregate != nullptr && lhsAsAggregate->getOp() == EOpImageLoad)
145 return true;
146
147 return false;
148}
149
steve-lunarg0de16da2016-10-08 10:54:52 -0600150//
steve-lunarg4f2da272016-10-10 15:24:57 -0600151// Return a TLayoutFormat corresponding to the given texture type.
152//
153TLayoutFormat HlslParseContext::getLayoutFromTxType(const TSourceLoc& loc, const TType& txType)
154{
155 const int components = txType.getVectorSize();
156
157 const auto select = [&](TLayoutFormat v1, TLayoutFormat v2, TLayoutFormat v4) {
158 return components == 1 ? v1 :
159 components == 2 ? v2 : v4;
160 };
161
162 switch (txType.getBasicType()) {
163 case EbtFloat: return select(ElfR32f, ElfRg32f, ElfRgba32f);
164 case EbtInt: return select(ElfR32i, ElfRg32i, ElfRgba32i);
165 case EbtUint: return select(ElfR32ui, ElfRg32ui, ElfRgba32ui);
166 default:
167 error(loc, "unknown basic type in image format", "", "");
168 return ElfNone;
169 }
170}
171
172//
steve-lunarg0de16da2016-10-08 10:54:52 -0600173// Both test and if necessary, spit out an error, to see if the node is really
174// an l-value that can be operated on this way.
175//
176// Returns true if there was an error.
177//
178bool HlslParseContext::lValueErrorCheck(const TSourceLoc& loc, const char* op, TIntermTyped* node)
179{
180 if (shouldConvertLValue(node)) {
181 // if we're writing to a texture, it must be an RW form.
182
183 TIntermAggregate* lhsAsAggregate = node->getAsAggregate();
184 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
185
186 if (!object->getType().getSampler().isImage()) {
187 error(loc, "operator[] on a non-RW texture must be an r-value", "", "");
188 return true;
189 }
190 }
191
192 // Let the base class check errors
193 return TParseContextBase::lValueErrorCheck(loc, op, node);
194}
steve-lunarg90707962016-10-07 19:35:40 -0600195
196//
197// This function handles l-value conversions and verifications. It uses, but is not synonymous
198// with lValueErrorCheck. That function accepts an l-value directly, while this one must be
199// given the surrounding tree - e.g, with an assignment, so we can convert the assign into a
200// series of other image operations.
201//
202// Most things are passed through unmodified, except for error checking.
203//
204TIntermTyped* HlslParseContext::handleLvalue(const TSourceLoc& loc, const char* op, TIntermTyped* node)
205{
steve-lunarg07830e82016-10-10 10:00:14 -0600206 if (node == nullptr)
207 return nullptr;
208
steve-lunarg90707962016-10-07 19:35:40 -0600209 TIntermBinary* nodeAsBinary = node->getAsBinaryNode();
210 TIntermUnary* nodeAsUnary = node->getAsUnaryNode();
211 TIntermAggregate* sequence = nullptr;
212
213 TIntermTyped* lhs = nodeAsUnary ? nodeAsUnary->getOperand() :
214 nodeAsBinary ? nodeAsBinary->getLeft() :
215 nullptr;
216
steve-lunarg90707962016-10-07 19:35:40 -0600217 // Early bail out if there is no conversion to apply
218 if (!shouldConvertLValue(lhs)) {
steve-lunarg0de16da2016-10-08 10:54:52 -0600219 if (lhs != nullptr)
220 if (lValueErrorCheck(loc, op, lhs))
221 return nullptr;
steve-lunarg90707962016-10-07 19:35:40 -0600222 return node;
223 }
224
225 // *** If we get here, we're going to apply some conversion to an l-value.
226
227 // Helper to create a load.
228 const auto makeLoad = [&](TIntermSymbol* rhsTmp, TIntermTyped* object, TIntermTyped* coord, const TType& derefType) {
229 TIntermAggregate* loadOp = new TIntermAggregate(EOpImageLoad);
230 loadOp->setLoc(loc);
231 loadOp->getSequence().push_back(object);
232 loadOp->getSequence().push_back(intermediate.addSymbol(*coord->getAsSymbolNode()));
233 loadOp->setType(derefType);
234
235 sequence = intermediate.growAggregate(sequence,
236 intermediate.addAssign(EOpAssign, rhsTmp, loadOp, loc),
237 loc);
238 };
239
240 // Helper to create a store.
241 const auto makeStore = [&](TIntermTyped* object, TIntermTyped* coord, TIntermSymbol* rhsTmp) {
242 TIntermAggregate* storeOp = new TIntermAggregate(EOpImageStore);
243 storeOp->getSequence().push_back(object);
244 storeOp->getSequence().push_back(coord);
245 storeOp->getSequence().push_back(intermediate.addSymbol(*rhsTmp));
246 storeOp->setLoc(loc);
247 storeOp->setType(TType(EbtVoid));
248
249 sequence = intermediate.growAggregate(sequence, storeOp);
250 };
251
252 // Helper to create an assign.
steve-lunargb3da8a92016-10-12 12:38:12 -0600253 const auto makeBinary = [&](TOperator op, TIntermTyped* lhs, TIntermTyped* rhs) {
steve-lunarg90707962016-10-07 19:35:40 -0600254 sequence = intermediate.growAggregate(sequence,
steve-lunargb3da8a92016-10-12 12:38:12 -0600255 intermediate.addBinaryNode(op, lhs, rhs, loc, lhs->getType()),
steve-lunarg90707962016-10-07 19:35:40 -0600256 loc);
257 };
258
259 // Helper to complete sequence by adding trailing variable, so we evaluate to the right value.
260 const auto finishSequence = [&](TIntermSymbol* rhsTmp, const TType& derefType) {
261 // Add a trailing use of the temp, so the sequence returns the proper value.
262 sequence = intermediate.growAggregate(sequence, intermediate.addSymbol(*rhsTmp));
263 sequence->setOperator(EOpSequence);
264 sequence->setLoc(loc);
265 sequence->setType(derefType);
266
267 return sequence;
268 };
269
270 // Helper to add unary op
steve-lunargb3da8a92016-10-12 12:38:12 -0600271 const auto makeUnary = [&](TOperator op, TIntermSymbol* rhsTmp) {
steve-lunarg90707962016-10-07 19:35:40 -0600272 sequence = intermediate.growAggregate(sequence,
steve-lunargb3da8a92016-10-12 12:38:12 -0600273 intermediate.addUnaryNode(op, intermediate.addSymbol(*rhsTmp), loc,
274 rhsTmp->getType()),
steve-lunarg90707962016-10-07 19:35:40 -0600275 loc);
276 };
277
278 // helper to create a temporary variable
279 const auto addTmpVar = [&](const char* name, const TType& derefType) {
280 TVariable* tmpVar = makeInternalVariable(name, derefType);
281 tmpVar->getWritableType().getQualifier().makeTemporary();
282 return intermediate.addSymbol(*tmpVar, loc);
283 };
284
285 TIntermAggregate* lhsAsAggregate = lhs->getAsAggregate();
286 TIntermTyped* object = lhsAsAggregate->getSequence()[0]->getAsTyped();
287 TIntermTyped* coord = lhsAsAggregate->getSequence()[1]->getAsTyped();
288
289 const TLayoutFormat fmt = object->getType().getQualifier().layoutFormat;
steve-lunarg90707962016-10-07 19:35:40 -0600290
steve-lunarg4f2da272016-10-10 15:24:57 -0600291 // We only handle this subset of the possible formats.
292 assert(fmt == ElfRgba32f || fmt == ElfRgba32i || fmt == ElfRgba32ui ||
293 fmt == ElfRg32f || fmt == ElfRg32i || fmt == ElfRg32ui ||
294 fmt == ElfR32f || fmt == ElfR32i || fmt == ElfR32ui);
295
296 const TType objDerefType(object->getType().getSampler().type, EvqTemporary,
297 TQualifier::getLayoutComponentCount(fmt));
steve-lunarg90707962016-10-07 19:35:40 -0600298
299 if (nodeAsBinary) {
300 TIntermTyped* rhs = nodeAsBinary->getRight();
301 const TOperator assignOp = nodeAsBinary->getOp();
302
303 bool isModifyOp = false;
304
305 switch (assignOp) {
306 case EOpAddAssign:
307 case EOpSubAssign:
308 case EOpMulAssign:
309 case EOpVectorTimesMatrixAssign:
310 case EOpVectorTimesScalarAssign:
311 case EOpMatrixTimesScalarAssign:
312 case EOpMatrixTimesMatrixAssign:
313 case EOpDivAssign:
314 case EOpModAssign:
315 case EOpAndAssign:
316 case EOpInclusiveOrAssign:
317 case EOpExclusiveOrAssign:
318 case EOpLeftShiftAssign:
319 case EOpRightShiftAssign:
320 isModifyOp = true;
321 // fall through...
322 case EOpAssign:
323 {
324 // Since this is an lvalue, we'll convert an image load to a sequence like this (to still provide the value):
325 // OpSequence
326 // OpImageStore(object, lhs, rhs)
327 // rhs
328 // But if it's not a simple symbol RHS (say, a fn call), we don't want to duplicate the RHS, so we'll convert
329 // instead to this:
330 // OpSequence
331 // rhsTmp = rhs
332 // OpImageStore(object, coord, rhsTmp)
333 // rhsTmp
334 // If this is a read-modify-write op, like +=, we issue:
335 // OpSequence
336 // coordtmp = load's param1
337 // rhsTmp = OpImageLoad(object, coordTmp)
338 // rhsTmp op= rhs
339 // OpImageStore(object, coordTmp, rhsTmp)
340 // rhsTmp
341
342 TIntermSymbol* rhsTmp = rhs->getAsSymbolNode();
343 TIntermTyped* coordTmp = coord;
344
345 if (rhsTmp == nullptr || isModifyOp) {
346 rhsTmp = addTmpVar("storeTemp", objDerefType);
347
348 // Assign storeTemp = rhs
349 if (isModifyOp) {
350 // We have to make a temp var for the coordinate, to avoid evaluating it twice.
351 coordTmp = addTmpVar("coordTemp", coord->getType());
steve-lunargb3da8a92016-10-12 12:38:12 -0600352 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
steve-lunarg90707962016-10-07 19:35:40 -0600353 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
354 }
355
356 // rhsTmp op= rhs.
steve-lunargb3da8a92016-10-12 12:38:12 -0600357 makeBinary(assignOp, intermediate.addSymbol(*rhsTmp), rhs);
steve-lunarg90707962016-10-07 19:35:40 -0600358 }
359
360 makeStore(object, coordTmp, rhsTmp); // add a store
361 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
362 }
363
364 default:
365 break;
366 }
367 }
368
369 if (nodeAsUnary) {
370 const TOperator assignOp = nodeAsUnary->getOp();
371
372 switch (assignOp) {
373 case EOpPreIncrement:
374 case EOpPreDecrement:
375 {
376 // We turn this into:
377 // OpSequence
378 // coordtmp = load's param1
379 // rhsTmp = OpImageLoad(object, coordTmp)
380 // rhsTmp op
381 // OpImageStore(object, coordTmp, rhsTmp)
382 // rhsTmp
383
384 TIntermSymbol* rhsTmp = addTmpVar("storeTemp", objDerefType);
385 TIntermTyped* coordTmp = addTmpVar("coordTemp", coord->getType());
386
steve-lunargb3da8a92016-10-12 12:38:12 -0600387 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
steve-lunarg90707962016-10-07 19:35:40 -0600388 makeLoad(rhsTmp, object, coordTmp, objDerefType); // rhsTmp = OpImageLoad(object, coordTmp)
steve-lunargb3da8a92016-10-12 12:38:12 -0600389 makeUnary(assignOp, rhsTmp); // op rhsTmp
steve-lunarg90707962016-10-07 19:35:40 -0600390 makeStore(object, coordTmp, rhsTmp); // OpImageStore(object, coordTmp, rhsTmp)
391 return finishSequence(rhsTmp, objDerefType); // return rhsTmp from sequence
392 }
393
394 case EOpPostIncrement:
395 case EOpPostDecrement:
396 {
397 // We turn this into:
398 // OpSequence
399 // coordtmp = load's param1
400 // rhsTmp1 = OpImageLoad(object, coordTmp)
401 // rhsTmp2 = rhsTmp1
402 // rhsTmp2 op
403 // OpImageStore(object, coordTmp, rhsTmp2)
404 // rhsTmp1 (pre-op value)
405 TIntermSymbol* rhsTmp1 = addTmpVar("storeTempPre", objDerefType);
406 TIntermSymbol* rhsTmp2 = addTmpVar("storeTempPost", objDerefType);
407 TIntermTyped* coordTmp = addTmpVar("coordTemp", coord->getType());
408
steve-lunargb3da8a92016-10-12 12:38:12 -0600409 makeBinary(EOpAssign, coordTmp, coord); // coordtmp = load[param1]
steve-lunarg90707962016-10-07 19:35:40 -0600410 makeLoad(rhsTmp1, object, coordTmp, objDerefType); // rhsTmp1 = OpImageLoad(object, coordTmp)
steve-lunargb3da8a92016-10-12 12:38:12 -0600411 makeBinary(EOpAssign, rhsTmp2, rhsTmp1); // rhsTmp2 = rhsTmp1
412 makeUnary(assignOp, rhsTmp2); // rhsTmp op
steve-lunarg90707962016-10-07 19:35:40 -0600413 makeStore(object, coordTmp, rhsTmp2); // OpImageStore(object, coordTmp, rhsTmp2)
414 return finishSequence(rhsTmp1, objDerefType); // return rhsTmp from sequence
steve-lunarg90707962016-10-07 19:35:40 -0600415 }
416
417 default:
418 break;
419 }
420 }
421
steve-lunarg0de16da2016-10-08 10:54:52 -0600422 if (lhs)
423 if (lValueErrorCheck(loc, op, lhs))
424 return nullptr;
steve-lunarg90707962016-10-07 19:35:40 -0600425
426 return node;
427}
428
John Kesseniche01a9bc2016-03-12 20:11:22 -0700429void HlslParseContext::handlePragma(const TSourceLoc& loc, const TVector<TString>& tokens)
430{
431 if (pragmaCallback)
432 pragmaCallback(loc.line, tokens);
433
434 if (tokens.size() == 0)
435 return;
436}
437
438//
439// Look at a '.' field selector string and change it into offsets
440// for a vector or scalar
441//
442// Returns true if there is no error.
443//
444bool HlslParseContext::parseVectorFields(const TSourceLoc& loc, const TString& compString, int vecSize, TVectorFields& fields)
445{
446 fields.num = (int)compString.size();
447 if (fields.num > 4) {
448 error(loc, "illegal vector field selection", compString.c_str(), "");
449 return false;
450 }
451
452 enum {
453 exyzw,
454 ergba,
455 estpq,
456 } fieldSet[4];
457
458 for (int i = 0; i < fields.num; ++i) {
459 switch (compString[i]) {
460 case 'x':
461 fields.offsets[i] = 0;
462 fieldSet[i] = exyzw;
463 break;
464 case 'r':
465 fields.offsets[i] = 0;
466 fieldSet[i] = ergba;
467 break;
468 case 's':
469 fields.offsets[i] = 0;
470 fieldSet[i] = estpq;
471 break;
472 case 'y':
473 fields.offsets[i] = 1;
474 fieldSet[i] = exyzw;
475 break;
476 case 'g':
477 fields.offsets[i] = 1;
478 fieldSet[i] = ergba;
479 break;
480 case 't':
481 fields.offsets[i] = 1;
482 fieldSet[i] = estpq;
483 break;
484 case 'z':
485 fields.offsets[i] = 2;
486 fieldSet[i] = exyzw;
487 break;
488 case 'b':
489 fields.offsets[i] = 2;
490 fieldSet[i] = ergba;
491 break;
492 case 'p':
493 fields.offsets[i] = 2;
494 fieldSet[i] = estpq;
495 break;
496
497 case 'w':
498 fields.offsets[i] = 3;
499 fieldSet[i] = exyzw;
500 break;
501 case 'a':
502 fields.offsets[i] = 3;
503 fieldSet[i] = ergba;
504 break;
505 case 'q':
506 fields.offsets[i] = 3;
507 fieldSet[i] = estpq;
508 break;
509 default:
510 error(loc, "illegal vector field selection", compString.c_str(), "");
511 return false;
512 }
513 }
514
515 for (int i = 0; i < fields.num; ++i) {
516 if (fields.offsets[i] >= vecSize) {
517 error(loc, "vector field selection out of range", compString.c_str(), "");
518 return false;
519 }
520
521 if (i > 0) {
522 if (fieldSet[i] != fieldSet[i - 1]) {
523 error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
524 return false;
525 }
526 }
527 }
528
529 return true;
530}
531
532//
John Kesseniche01a9bc2016-03-12 20:11:22 -0700533// Handle seeing a variable identifier in the grammar.
534//
John Kesseniche6e74942016-06-11 16:43:14 -0600535TIntermTyped* HlslParseContext::handleVariable(const TSourceLoc& loc, TSymbol* symbol, const TString* string)
John Kesseniche01a9bc2016-03-12 20:11:22 -0700536{
John Kesseniche6e74942016-06-11 16:43:14 -0600537 if (symbol == nullptr)
538 symbol = symbolTable.find(*string);
539 if (symbol && symbol->getAsVariable() && symbol->getAsVariable()->isUserType()) {
540 error(loc, "expected symbol, not user-defined type", string->c_str(), "");
541 return nullptr;
542 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700543
544 // Error check for requiring specific extensions present.
545 if (symbol && symbol->getNumExtensions())
546 requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
547
John Kesseniche01a9bc2016-03-12 20:11:22 -0700548 const TVariable* variable;
549 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : nullptr;
John Kesseniche6e74942016-06-11 16:43:14 -0600550 TIntermTyped* node = nullptr;
John Kesseniche01a9bc2016-03-12 20:11:22 -0700551 if (anon) {
552 // It was a member of an anonymous container.
553
554 // Create a subtree for its dereference.
555 variable = anon->getAnonContainer().getAsVariable();
556 TIntermTyped* container = intermediate.addSymbol(*variable, loc);
557 TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
558 node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
559
560 node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
561 if (node->getType().hiddenMember())
562 error(loc, "member of nameless block was not redeclared", string->c_str(), "");
563 } else {
564 // Not a member of an anonymous container.
565
566 // The symbol table search was done in the lexical phase.
567 // See if it was a variable.
568 variable = symbol ? symbol->getAsVariable() : nullptr;
569 if (variable) {
570 if ((variable->getType().getBasicType() == EbtBlock ||
571 variable->getType().getBasicType() == EbtStruct) && variable->getType().getStruct() == nullptr) {
572 error(loc, "cannot be used (maybe an instance name is needed)", string->c_str(), "");
573 variable = nullptr;
574 }
575 } else {
576 if (symbol)
577 error(loc, "variable name expected", string->c_str(), "");
578 }
579
580 // Recovery, if it wasn't found or was not a variable.
581 if (! variable)
582 variable = new TVariable(string, TType(EbtVoid));
583
584 if (variable->getType().getQualifier().isFrontEndConstant())
585 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
586 else
587 node = intermediate.addSymbol(*variable, loc);
588 }
589
590 if (variable->getType().getQualifier().isIo())
591 intermediate.addIoAccessed(*string);
592
593 return node;
594}
595
596//
steve-lunarg6b43d272016-10-06 20:12:24 -0600597// Handle operator[] on any objects it applies to. Currently:
598// Textures
599// Buffers
600//
601TIntermTyped* HlslParseContext::handleBracketOperator(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
602{
603 // handle r-value operator[] on textures and images. l-values will be processed later.
604 if (base->getType().getBasicType() == EbtSampler && !base->isArray()) {
605 const TSampler& sampler = base->getType().getSampler();
606 if (sampler.isImage() || sampler.isTexture()) {
steve-lunarg4f2da272016-10-10 15:24:57 -0600607 const int vecSize = TQualifier::getLayoutComponentCount(base->getType().getQualifier().layoutFormat);
steve-lunarg07830e82016-10-10 10:00:14 -0600608 TIntermAggregate* load = new TIntermAggregate(sampler.isImage() ? EOpImageLoad : EOpTextureFetch);
steve-lunarg6b43d272016-10-06 20:12:24 -0600609
610 load->setType(TType(sampler.type, EvqTemporary, vecSize));
611 load->setLoc(loc);
612 load->getSequence().push_back(base);
613 load->getSequence().push_back(index);
steve-lunarg07830e82016-10-10 10:00:14 -0600614
615 // Textures need a MIP. First indirection is always to mip 0. If there's another, we'll add it
616 // later.
617 if (sampler.isTexture())
618 load->getSequence().push_back(intermediate.addConstantUnion(0, loc, true));
619
steve-lunarg6b43d272016-10-06 20:12:24 -0600620 return load;
621 }
622 }
623
624 return nullptr;
625}
626
627//
John Kesseniche01a9bc2016-03-12 20:11:22 -0700628// Handle seeing a base[index] dereference in the grammar.
629//
630TIntermTyped* HlslParseContext::handleBracketDereference(const TSourceLoc& loc, TIntermTyped* base, TIntermTyped* index)
631{
steve-lunarg6b43d272016-10-06 20:12:24 -0600632 TIntermTyped* result = handleBracketOperator(loc, base, index);
633
634 if (result != nullptr)
635 return result; // it was handled as an operator[]
John Kesseniche01a9bc2016-03-12 20:11:22 -0700636
steve-lunargcf43e662016-09-22 14:35:23 -0600637 bool flattened = false;
John Kesseniche01a9bc2016-03-12 20:11:22 -0700638 int indexValue = 0;
639 if (index->getQualifier().storage == EvqConst) {
640 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
641 checkIndex(loc, base->getType(), indexValue);
642 }
643
644 variableCheck(base);
645 if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
646 if (base->getAsSymbolNode())
647 error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
648 else
649 error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
650 } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
651 return intermediate.foldDereference(base, indexValue, loc);
652 else {
653 // at least one of base and index is variable...
654
steve-lunarge0b9deb2016-09-16 13:26:37 -0600655 if (base->getAsSymbolNode() && shouldFlatten(base->getType())) {
656 if (index->getQualifier().storage != EvqConst)
657 error(loc, "Invalid variable index to flattened uniform array", base->getAsSymbolNode()->getName().c_str(), "");
658
659 result = flattenAccess(base, indexValue);
steve-lunargcf43e662016-09-22 14:35:23 -0600660 flattened = (result != base);
John Kesseniche01a9bc2016-03-12 20:11:22 -0700661 } else {
steve-lunarge0b9deb2016-09-16 13:26:37 -0600662 if (index->getQualifier().storage == EvqConst) {
663 if (base->getType().isImplicitlySizedArray())
664 updateImplicitArraySize(loc, base, indexValue);
665 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
666 } else {
667 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
668 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700669 }
670 }
671
672 if (result == nullptr) {
673 // Insert dummy error-recovery result
674 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
675 } else {
steve-lunargcf43e662016-09-22 14:35:23 -0600676 // If the array reference was flattened, it has the correct type. E.g, if it was
677 // a uniform array, it was flattened INTO a set of scalar uniforms, not scalar temps.
678 // In that case, we preserve the qualifiers.
679 if (!flattened) {
680 // Insert valid dereferenced result
681 TType newType(base->getType(), 0); // dereferenced type
682 if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
683 newType.getQualifier().storage = EvqConst;
684 else
685 newType.getQualifier().storage = EvqTemporary;
686 result->setType(newType);
687 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700688 }
689
690 return result;
691}
692
John Kessenich7f349c72016-07-08 22:09:10 -0600693void HlslParseContext::checkIndex(const TSourceLoc& /*loc*/, const TType& /*type*/, int& /*index*/)
John Kesseniche01a9bc2016-03-12 20:11:22 -0700694{
695 // HLSL todo: any rules for index fixups?
696}
697
John Kesseniche01a9bc2016-03-12 20:11:22 -0700698// Handle seeing a binary node with a math operation.
699TIntermTyped* HlslParseContext::handleBinaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
700{
701 TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
702 if (! result)
703 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
704
705 return result;
706}
707
708// Handle seeing a unary node with a math operation.
709TIntermTyped* HlslParseContext::handleUnaryMath(const TSourceLoc& loc, const char* str, TOperator op, TIntermTyped* childNode)
710{
711 TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
712
713 if (result)
714 return result;
715 else
716 unaryOpError(loc, str, childNode->getCompleteString());
717
718 return childNode;
719}
720
721//
722// Handle seeing a base.field dereference in the grammar.
723//
724TIntermTyped* HlslParseContext::handleDotDereference(const TSourceLoc& loc, TIntermTyped* base, const TString& field)
725{
726 variableCheck(base);
727
728 //
LoopDawg4886f692016-06-29 10:58:58 -0600729 // methods can't be resolved until we later see the function-calling syntax.
John Kesseniche01a9bc2016-03-12 20:11:22 -0700730 // Save away the name in the AST for now. Processing is completed in
LoopDawg4886f692016-06-29 10:58:58 -0600731 // handleLengthMethod(), etc.
John Kesseniche01a9bc2016-03-12 20:11:22 -0700732 //
733 if (field == "length") {
734 return intermediate.addMethod(base, TType(EbtInt), &field, loc);
LoopDawg4886f692016-06-29 10:58:58 -0600735 } else if (field == "CalculateLevelOfDetail" ||
736 field == "CalculateLevelOfDetailUnclamped" ||
737 field == "Gather" ||
steve-lunarg7dfcf4d2016-07-31 10:37:02 -0600738 field == "GatherRed" ||
739 field == "GatherGreen" ||
740 field == "GatherBlue" ||
741 field == "GatherAlpha" ||
742 field == "GatherCmp" ||
743 field == "GatherCmpRed" ||
744 field == "GatherCmpGreen" ||
745 field == "GatherCmpBlue" ||
746 field == "GatherCmpAlpha" ||
LoopDawg4886f692016-06-29 10:58:58 -0600747 field == "GetDimensions" ||
748 field == "GetSamplePosition" ||
749 field == "Load" ||
750 field == "Sample" ||
751 field == "SampleBias" ||
752 field == "SampleCmp" ||
753 field == "SampleCmpLevelZero" ||
754 field == "SampleGrad" ||
755 field == "SampleLevel") {
756 // If it's not a method on a sampler object, we fall through in case it is a struct member.
757 if (base->getType().getBasicType() == EbtSampler) {
steve-lunarg6b43d272016-10-06 20:12:24 -0600758 const TSampler& sampler = base->getType().getSampler();
759 if (! sampler.isPureSampler()) {
760 const int vecSize = sampler.isShadow() ? 1 : 4; // TODO: handle arbitrary sample return sizes
761 return intermediate.addMethod(base, TType(sampler.type, EvqTemporary, vecSize), &field, loc);
LoopDawg4886f692016-06-29 10:58:58 -0600762 }
763 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700764 }
765
766 // It's not .length() if we get to here.
767
768 if (base->isArray()) {
769 error(loc, "cannot apply to an array:", ".", field.c_str());
770
771 return base;
772 }
773
774 // It's neither an array nor .length() if we get here,
775 // leaving swizzles and struct/block dereferences.
776
777 TIntermTyped* result = base;
778 if (base->isVector() || base->isScalar()) {
779 TVectorFields fields;
780 if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
781 fields.num = 1;
782 fields.offsets[0] = 0;
783 }
784
785 if (base->isScalar()) {
786 if (fields.num == 1)
787 return result;
788 else {
789 TType type(base->getBasicType(), EvqTemporary, fields.num);
John Kessenicha26a5172016-07-28 15:29:35 -0600790 return addConstructor(loc, base, type);
John Kesseniche01a9bc2016-03-12 20:11:22 -0700791 }
792 }
John Kessenich7d01bd62016-09-02 22:21:25 -0600793 if (base->getVectorSize() == 1) {
794 TType scalarType(base->getBasicType(), EvqTemporary, 1);
795 if (fields.num == 1)
796 return addConstructor(loc, base, scalarType);
797 else {
798 TType vectorType(base->getBasicType(), EvqTemporary, fields.num);
799 return addConstructor(loc, addConstructor(loc, base, scalarType), vectorType);
800 }
801 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700802
803 if (base->getType().getQualifier().isFrontEndConstant())
804 result = intermediate.foldSwizzle(base, fields, loc);
805 else {
806 if (fields.num == 1) {
807 TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
808 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
John Kessenichf6640762016-08-01 19:44:00 -0600809 result->setType(TType(base->getBasicType(), EvqTemporary));
John Kesseniche01a9bc2016-03-12 20:11:22 -0700810 } else {
811 TString vectorString = field;
812 TIntermTyped* index = intermediate.addSwizzle(fields, loc);
813 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
814 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int)vectorString.size()));
815 }
816 }
817 } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
818 const TTypeList* fields = base->getType().getStruct();
819 bool fieldFound = false;
820 int member;
821 for (member = 0; member < (int)fields->size(); ++member) {
822 if ((*fields)[member].type->getFieldName() == field) {
823 fieldFound = true;
824 break;
825 }
826 }
827 if (fieldFound) {
John Kessenichcd0a78a2016-09-09 16:32:09 -0600828 if (base->getAsSymbolNode() && shouldFlatten(base->getType()))
829 result = flattenAccess(base, member);
John Kesseniche01a9bc2016-03-12 20:11:22 -0700830 else {
John Kessenichcd0a78a2016-09-09 16:32:09 -0600831 if (base->getType().getQualifier().storage == EvqConst)
832 result = intermediate.foldDereference(base, member, loc);
833 else {
834 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
835 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
836 result->setType(*(*fields)[member].type);
837 }
John Kesseniche01a9bc2016-03-12 20:11:22 -0700838 }
839 } else
840 error(loc, "no such field in structure", field.c_str(), "");
841 } else
842 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
843
844 return result;
845}
846
steve-lunarge0b9deb2016-09-16 13:26:37 -0600847// Is this an IO variable that can't be passed down the stack?
John Kessenichcd0a78a2016-09-09 16:32:09 -0600848// E.g., pipeline inputs to the vertex stage and outputs from the fragment stage.
steve-lunarge0b9deb2016-09-16 13:26:37 -0600849bool HlslParseContext::shouldFlattenIO(const TType& type) const
John Kessenichcd0a78a2016-09-09 16:32:09 -0600850{
John Kessenich6fccb3c2016-09-19 16:01:41 -0600851 if (! inEntryPoint)
John Kessenichdeb49402016-09-12 11:55:47 -0600852 return false;
853
John Kessenichcd0a78a2016-09-09 16:32:09 -0600854 const TStorageQualifier qualifier = type.getQualifier().storage;
855
856 return type.isStruct() &&
John Kessenichf8e494c2016-09-16 01:52:14 -0600857 (qualifier == EvqVaryingIn ||
858 qualifier == EvqVaryingOut);
John Kessenichcd0a78a2016-09-09 16:32:09 -0600859}
860
steve-lunarge0b9deb2016-09-16 13:26:37 -0600861// Is this a uniform array which should be flattened?
862bool HlslParseContext::shouldFlattenUniform(const TType& type) const
863{
864 const TStorageQualifier qualifier = type.getQualifier().storage;
865
866 return type.isArray() &&
867 intermediate.getFlattenUniformArrays() &&
steve-lunargbc9b7652016-09-29 08:43:22 -0600868 qualifier == EvqUniform &&
John Kessenichf571d0c2016-10-01 12:35:01 -0600869 type.isOpaque();
steve-lunarge0b9deb2016-09-16 13:26:37 -0600870}
871
872void HlslParseContext::flatten(const TSourceLoc& loc, const TVariable& variable)
873{
874 const TType& type = variable.getType();
875
876 // Presently, flattening of structure arrays is unimplemented.
877 // We handle one, or the other.
878 if (type.isArray() && type.isStruct()) {
879 error(loc, "cannot flatten structure array", variable.getName().c_str(), "");
880 }
881
882 if (type.isStruct())
883 flattenStruct(variable);
884
885 if (type.isArray())
886 flattenArray(loc, variable);
887}
888
John Kessenichf9115002016-09-18 23:10:22 -0600889// Figure out the mapping between an aggregate's top members and an
John Kessenichcd0a78a2016-09-09 16:32:09 -0600890// equivalent set of individual variables.
891//
John Kessenich6b71c402016-09-19 22:16:09 -0600892// N.B. Erases memory of I/O-related annotations in the original type's member,
893// effecting a transfer of this information to the flattened variable form.
894//
John Kessenichcd0a78a2016-09-09 16:32:09 -0600895// Assumes shouldFlatten() or equivalent was called first.
896//
897// TODO: generalize this to arbitrary nesting?
steve-lunarge0b9deb2016-09-16 13:26:37 -0600898void HlslParseContext::flattenStruct(const TVariable& variable)
John Kessenichcd0a78a2016-09-09 16:32:09 -0600899{
900 TVector<TVariable*> memberVariables;
901
902 auto members = *variable.getType().getStruct();
John Kessenichcd0a78a2016-09-09 16:32:09 -0600903 for (int member = 0; member < (int)members.size(); ++member) {
John Kessenich7dc630f2016-09-16 01:44:43 -0600904 TVariable* memberVariable = makeInternalVariable(members[member].type->getFieldName().c_str(),
905 *members[member].type);
John Kessenich34e7ee72016-09-16 17:10:39 -0600906 mergeQualifiers(memberVariable->getWritableType().getQualifier(), variable.getType().getQualifier());
John Kessenichcd0a78a2016-09-09 16:32:09 -0600907 memberVariables.push_back(memberVariable);
John Kessenich6b71c402016-09-19 22:16:09 -0600908
909 // N.B. Erase I/O-related annotations from the source-type member.
910 members[member].type->getQualifier().makeTemporary();
John Kessenichcd0a78a2016-09-09 16:32:09 -0600911 }
912
913 flattenMap[variable.getUniqueId()] = memberVariables;
914}
915
steve-lunarge0b9deb2016-09-16 13:26:37 -0600916// Figure out mapping between an array's members and an
917// equivalent set of individual variables.
918//
919// Assumes shouldFlatten() or equivalent was called first.
920void HlslParseContext::flattenArray(const TSourceLoc& loc, const TVariable& variable)
921{
922 const TType& type = variable.getType();
923 assert(type.isArray());
924
925 if (type.isImplicitlySizedArray())
926 error(loc, "cannot flatten implicitly sized array", variable.getName().c_str(), "");
927
928 if (type.getArraySizes()->getNumDims() != 1)
929 error(loc, "cannot flatten multi-dimensional array", variable.getName().c_str(), "");
930
931 const int size = type.getCumulativeArraySize();
932
933 TVector<TVariable*> memberVariables;
934
935 const TType dereferencedType(type, 0);
936 int binding = type.getQualifier().layoutBinding;
937
938 if (dereferencedType.isStruct() || dereferencedType.isArray()) {
939 error(loc, "cannot flatten array of aggregate types", variable.getName().c_str(), "");
940 }
941
942 for (int element=0; element < size; ++element) {
943 char elementNumBuf[20]; // sufficient for MAXINT
944 snprintf(elementNumBuf, sizeof(elementNumBuf)-1, "[%d]", element);
945 const TString memberName = variable.getName() + elementNumBuf;
946
947 TVariable* memberVariable = makeInternalVariable(memberName.c_str(), dereferencedType);
948 memberVariable->getWritableType().getQualifier() = variable.getType().getQualifier();
949
950 memberVariable->getWritableType().getQualifier().layoutBinding = binding;
951
952 if (binding != TQualifier::layoutBindingEnd)
953 ++binding;
954
955 memberVariables.push_back(memberVariable);
956 intermediate.addSymbolLinkageNode(linkage, *memberVariable);
957 }
958
959 flattenMap[variable.getUniqueId()] = memberVariables;
960}
961
962// Turn an access into an aggregate that was flattened to instead be
963// an access to the individual variable the member was flattened to.
John Kessenichcd0a78a2016-09-09 16:32:09 -0600964// Assumes shouldFlatten() or equivalent was called first.
965TIntermTyped* HlslParseContext::flattenAccess(TIntermTyped* base, int member)
966{
967 const TIntermSymbol& symbolNode = *base->getAsSymbolNode();
968
969 if (flattenMap.find(symbolNode.getId()) == flattenMap.end())
970 return base;
971
972 const TVariable* memberVariable = flattenMap[symbolNode.getId()][member];
973 return intermediate.addSymbol(*memberVariable);
974}
975
John Kessenich7dc630f2016-09-16 01:44:43 -0600976// Variables that correspond to the user-interface in and out of a stage
977// (not the built-in interface) are assigned locations and
978// registered as a linkage node (part of the stage's external interface).
979//
980// Assumes it is called in the order in which locations should be assigned.
981void HlslParseContext::assignLocations(TVariable& variable)
982{
983 const auto assignLocation = [&](TVariable& variable) {
984 const TQualifier& qualifier = variable.getType().getQualifier();
985 if (qualifier.storage == EvqVaryingIn || qualifier.storage == EvqVaryingOut) {
986 if (qualifier.builtIn == EbvNone) {
987 if (qualifier.storage == EvqVaryingIn) {
988 variable.getWritableType().getQualifier().layoutLocation = nextInLocation;
989 nextInLocation += intermediate.computeTypeLocationSize(variable.getType());
990 } else {
991 variable.getWritableType().getQualifier().layoutLocation = nextOutLocation;
992 nextOutLocation += intermediate.computeTypeLocationSize(variable.getType());
993 }
994 }
995 intermediate.addSymbolLinkageNode(linkage, variable);
996 }
997 };
998
999 if (shouldFlatten(variable.getType())) {
1000 auto& memberList = flattenMap[variable.getUniqueId()];
1001 for (auto member = memberList.begin(); member != memberList.end(); ++member)
1002 assignLocation(**member);
1003 } else
1004 assignLocation(variable);
1005}
1006
John Kesseniche01a9bc2016-03-12 20:11:22 -07001007//
1008// Handle seeing a function declarator in the grammar. This is the precursor
1009// to recognizing a function prototype or function definition.
1010//
John Kessenicha3051662016-09-02 19:13:36 -06001011TFunction& HlslParseContext::handleFunctionDeclarator(const TSourceLoc& loc, TFunction& function, bool prototype)
John Kesseniche01a9bc2016-03-12 20:11:22 -07001012{
1013 //
1014 // Multiple declarations of the same function name are allowed.
1015 //
1016 // If this is a definition, the definition production code will check for redefinitions
1017 // (we don't know at this point if it's a definition or not).
1018 //
John Kesseniche01a9bc2016-03-12 20:11:22 -07001019 bool builtIn;
1020 TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
1021 const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
1022
1023 if (prototype) {
1024 // All built-in functions are defined, even though they don't have a body.
1025 // Count their prototype as a definition instead.
1026 if (symbolTable.atBuiltInLevel())
1027 function.setDefined();
1028 else {
1029 if (prevDec && ! builtIn)
1030 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
1031 function.setPrototyped();
1032 }
1033 }
1034
1035 // This insert won't actually insert it if it's a duplicate signature, but it will still check for
1036 // other forms of name collisions.
1037 if (! symbolTable.insert(function))
1038 error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
1039
1040 //
1041 // If this is a redeclaration, it could also be a definition,
1042 // in which case, we need to use the parameter names from this one, and not the one that's
1043 // being redeclared. So, pass back this declaration, not the one in the symbol table.
1044 //
John Kessenicha3051662016-09-02 19:13:36 -06001045 return function;
John Kesseniche01a9bc2016-03-12 20:11:22 -07001046}
1047
1048//
1049// Handle seeing the function prototype in front of a function definition in the grammar.
1050// The body is handled after this function returns.
1051//
1052TIntermAggregate* HlslParseContext::handleFunctionDefinition(const TSourceLoc& loc, TFunction& function)
1053{
1054 currentCaller = function.getMangledName();
1055 TSymbol* symbol = symbolTable.find(function.getMangledName());
1056 TFunction* prevDec = symbol ? symbol->getAsFunction() : nullptr;
1057
1058 if (! prevDec)
1059 error(loc, "can't find function", function.getName().c_str(), "");
1060 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
1061 // as it would have just been put in the symbol table. Otherwise, we're looking up
1062 // an earlier occurrence.
1063
1064 if (prevDec && prevDec->isDefined()) {
1065 // Then this function already has a body.
1066 error(loc, "function already has a body", function.getName().c_str(), "");
1067 }
1068 if (prevDec && ! prevDec->isDefined()) {
1069 prevDec->setDefined();
1070
1071 // Remember the return type for later checking for RETURN statements.
1072 currentFunctionType = &(prevDec->getType());
1073 } else
1074 currentFunctionType = new TType(EbtVoid);
1075 functionReturnsValue = false;
1076
John Kessenicheee9d532016-09-19 18:09:30 -06001077 inEntryPoint = function.getName().compare(intermediate.getEntryPointName().c_str()) == 0;
John Kessenich6fccb3c2016-09-19 16:01:41 -06001078 if (inEntryPoint) {
John Kessenicheee9d532016-09-19 18:09:30 -06001079 intermediate.setEntryPointMangledName(function.getMangledName().c_str());
John Kessenich2572b192016-09-19 23:12:48 -06001080 intermediate.incrementEntryPointCount();
John Kessenich6fccb3c2016-09-19 16:01:41 -06001081 remapEntryPointIO(function);
John Kessenich7dc630f2016-09-16 01:44:43 -06001082 if (entryPointOutput) {
1083 if (shouldFlatten(entryPointOutput->getType()))
steve-lunarge0b9deb2016-09-16 13:26:37 -06001084 flatten(loc, *entryPointOutput);
John Kessenich7dc630f2016-09-16 01:44:43 -06001085 assignLocations(*entryPointOutput);
1086 }
1087 } else
John Kessenich6fccb3c2016-09-19 16:01:41 -06001088 remapNonEntryPointIO(function);
John Kesseniche01a9bc2016-03-12 20:11:22 -07001089
John Kessenich6dbc0a72016-09-27 19:13:05 -06001090 // Insert the $Global constant buffer.
1091 // TODO: this design fails if new members are declared between function definitions.
1092 if (! insertGlobalUniformBlock())
1093 error(loc, "failed to insert the global constant buffer", "uniform", "");
1094
John Kesseniche01a9bc2016-03-12 20:11:22 -07001095 //
1096 // New symbol table scope for body of function plus its arguments
1097 //
John Kessenich077e0522016-06-09 02:02:17 -06001098 pushScope();
John Kesseniche01a9bc2016-03-12 20:11:22 -07001099
1100 //
1101 // Insert parameters into the symbol table.
1102 // If the parameter has no name, it's not an error, just don't insert it
1103 // (could be used for unused args).
1104 //
John Kessenich7dc630f2016-09-16 01:44:43 -06001105 // Also, accumulate the list of parameters into the AST, so lower level code
John Kesseniche01a9bc2016-03-12 20:11:22 -07001106 // knows where to find parameters.
1107 //
1108 TIntermAggregate* paramNodes = new TIntermAggregate;
1109 for (int i = 0; i < function.getParamCount(); i++) {
1110 TParameter& param = function[i];
1111 if (param.name != nullptr) {
1112 TVariable *variable = new TVariable(param.name, *param.type);
1113
1114 // Insert the parameters with name in the symbol table.
1115 if (! symbolTable.insert(*variable))
1116 error(loc, "redefinition", variable->getName().c_str(), "");
1117 else {
John Kessenich7dc630f2016-09-16 01:44:43 -06001118 // get IO straightened out
John Kessenich6fccb3c2016-09-19 16:01:41 -06001119 if (inEntryPoint) {
John Kessenich7dc630f2016-09-16 01:44:43 -06001120 if (shouldFlatten(*param.type))
steve-lunarge0b9deb2016-09-16 13:26:37 -06001121 flatten(loc, *variable);
John Kessenich7dc630f2016-09-16 01:44:43 -06001122 assignLocations(*variable);
1123 }
1124
John Kesseniche01a9bc2016-03-12 20:11:22 -07001125 // Transfer ownership of name pointer to symbol table.
1126 param.name = nullptr;
1127
John Kessenich7dc630f2016-09-16 01:44:43 -06001128 // Add the parameter to the AST
John Kesseniche01a9bc2016-03-12 20:11:22 -07001129 paramNodes = intermediate.growAggregate(paramNodes,
John Kessenich7dc630f2016-09-16 01:44:43 -06001130 intermediate.addSymbol(*variable, loc),
1131 loc);
John Kesseniche01a9bc2016-03-12 20:11:22 -07001132 }
1133 } else
John Kessenich1c7e7072016-04-03 20:36:48 -06001134 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(*param.type, loc), loc);
John Kesseniche01a9bc2016-03-12 20:11:22 -07001135 }
1136 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
1137 loopNestingLevel = 0;
John Kesseniche01a9bc2016-03-12 20:11:22 -07001138 controlFlowNestingLevel = 0;
1139 postMainReturn = false;
1140
1141 return paramNodes;
1142}
1143
John Kessenicha3051662016-09-02 19:13:36 -06001144void HlslParseContext::handleFunctionBody(const TSourceLoc& loc, TFunction& function, TIntermNode* functionBody, TIntermNode*& node)
1145{
1146 node = intermediate.growAggregate(node, functionBody);
1147 intermediate.setAggregateOperator(node, EOpFunction, function.getType(), loc);
1148 node->getAsAggregate()->setName(function.getMangledName().c_str());
1149
1150 popScope();
1151
1152 if (function.getType().getBasicType() != EbtVoid && ! functionReturnsValue)
1153 error(loc, "function does not return a value:", "", function.getName().c_str());
1154}
1155
John Kessenich830b0cc2016-08-29 18:10:47 -06001156// AST I/O is done through shader globals declared in the 'in' or 'out'
1157// storage class. An HLSL entry point has a return value, input parameters
1158// and output parameters. These need to get remapped to the AST I/O.
John Kessenich6fccb3c2016-09-19 16:01:41 -06001159void HlslParseContext::remapEntryPointIO(TFunction& function)
John Kessenich830b0cc2016-08-29 18:10:47 -06001160{
1161 // Will auto-assign locations here to the inputs/outputs defined by the entry point
John Kessenich830b0cc2016-08-29 18:10:47 -06001162
John Kessenich7dc630f2016-09-16 01:44:43 -06001163 const auto remapType = [&](TType& type) {
1164 const auto remapBuiltInType = [&](TType& type) {
1165 switch (type.getQualifier().builtIn) {
1166 case EbvFragDepthGreater:
1167 intermediate.setDepth(EldGreater);
1168 type.getQualifier().builtIn = EbvFragDepth;
1169 break;
1170 case EbvFragDepthLesser:
1171 intermediate.setDepth(EldLess);
1172 type.getQualifier().builtIn = EbvFragDepth;
1173 break;
1174 default:
1175 break;
1176 }
1177 };
1178 remapBuiltInType(type);
1179 if (type.isStruct()) {
1180 auto members = *type.getStruct();
1181 for (auto member = members.begin(); member != members.end(); ++member)
1182 remapBuiltInType(*member->type);
John Kessenich9e079532016-09-02 20:05:19 -06001183 }
1184 };
1185
John Kessenich830b0cc2016-08-29 18:10:47 -06001186 // return value is actually a shader-scoped output (out)
1187 if (function.getType().getBasicType() != EbtVoid) {
1188 entryPointOutput = makeInternalVariable("@entryPointOutput", function.getType());
1189 entryPointOutput->getWritableType().getQualifier().storage = EvqVaryingOut;
John Kessenich7dc630f2016-09-16 01:44:43 -06001190 remapType(function.getWritableType());
John Kessenich830b0cc2016-08-29 18:10:47 -06001191 }
1192
1193 // parameters are actually shader-scoped inputs and outputs (in or out)
1194 for (int i = 0; i < function.getParamCount(); i++) {
John Kessenichcd0a78a2016-09-09 16:32:09 -06001195 TType& paramType = *function[i].type;
John Kessenich7dc630f2016-09-16 01:44:43 -06001196 paramType.getQualifier().storage = paramType.getQualifier().isParamInput() ? EvqVaryingIn : EvqVaryingOut;
1197 remapType(paramType);
John Kessenich830b0cc2016-08-29 18:10:47 -06001198 }
1199}
1200
John Kessenich07350f32016-09-02 20:23:27 -06001201// An HLSL function that looks like an entry point, but is not,
1202// declares entry point IO built-ins, but these have to be undone.
John Kessenich6fccb3c2016-09-19 16:01:41 -06001203void HlslParseContext::remapNonEntryPointIO(TFunction& function)
John Kessenich07350f32016-09-02 20:23:27 -06001204{
1205 const auto remapBuiltInType = [&](TType& type) { type.getQualifier().builtIn = EbvNone; };
1206
1207 // return value
1208 if (function.getType().getBasicType() != EbtVoid)
1209 remapBuiltInType(function.getWritableType());
1210
1211 // parameters
1212 for (int i = 0; i < function.getParamCount(); i++)
1213 remapBuiltInType(*function[i].type);
1214}
1215
steve-lunargc4a13072016-08-09 11:28:03 -06001216// Handle function returns, including type conversions to the function return type
1217// if necessary.
1218TIntermNode* HlslParseContext::handleReturnValue(const TSourceLoc& loc, TIntermTyped* value)
1219{
John Kessenicha3051662016-09-02 19:13:36 -06001220 functionReturnsValue = true;
John Kessenich6a70eb72016-08-28 15:00:23 -06001221
steve-lunargc4a13072016-08-09 11:28:03 -06001222 if (currentFunctionType->getBasicType() == EbtVoid) {
1223 error(loc, "void function cannot return a value", "return", "");
1224 return intermediate.addBranch(EOpReturn, loc);
1225 } else if (*currentFunctionType != value->getType()) {
John Kessenich087a4542016-10-06 16:56:54 -06001226 value = intermediate.addConversion(EOpReturn, *currentFunctionType, value);
1227 if (value && *currentFunctionType != value->getType())
1228 value = intermediate.addShapeConversion(EOpReturn, *currentFunctionType, value);
1229 if (value == nullptr) {
steve-lunargc4a13072016-08-09 11:28:03 -06001230 error(loc, "type does not match, or is not convertible to, the function's return type", "return", "");
John Kessenich087a4542016-10-06 16:56:54 -06001231 return value;
steve-lunargc4a13072016-08-09 11:28:03 -06001232 }
John Kessenich6a70eb72016-08-28 15:00:23 -06001233 }
1234
1235 // The entry point needs to send any return value to the entry-point output instead.
1236 // So, a subtree is built up, as a two-part sequence, with the first part being an
1237 // assignment subtree, and the second part being a return with no value.
1238 //
1239 // Otherwise, for a non entry point, just return a return statement.
John Kessenich6fccb3c2016-09-19 16:01:41 -06001240 if (inEntryPoint) {
John Kessenich6a70eb72016-08-28 15:00:23 -06001241 assert(entryPointOutput != nullptr); // should have been error tested at the beginning
1242 TIntermSymbol* left = new TIntermSymbol(entryPointOutput->getUniqueId(), entryPointOutput->getName(),
1243 entryPointOutput->getType());
John Kessenich087a4542016-10-06 16:56:54 -06001244 TIntermNode* returnSequence = handleAssign(loc, EOpAssign, left, value);
John Kessenich6a70eb72016-08-28 15:00:23 -06001245 returnSequence = intermediate.makeAggregate(returnSequence);
John Kessenicha08c9292016-10-01 17:17:55 -06001246 returnSequence = intermediate.growAggregate(returnSequence, intermediate.addBranch(EOpReturn, loc), loc);
John Kessenich6a70eb72016-08-28 15:00:23 -06001247 returnSequence->getAsAggregate()->setOperator(EOpSequence);
1248
1249 return returnSequence;
steve-lunargc4a13072016-08-09 11:28:03 -06001250 } else
1251 return intermediate.addBranch(EOpReturn, value, loc);
1252}
1253
John Kessenich4678ca92016-05-13 09:33:42 -06001254void HlslParseContext::handleFunctionArgument(TFunction* function, TIntermTyped*& arguments, TIntermTyped* newArg)
John Kessenichd016be12016-03-13 11:24:20 -06001255{
1256 TParameter param = { 0, new TType };
John Kessenich4678ca92016-05-13 09:33:42 -06001257 param.type->shallowCopy(newArg->getType());
John Kessenichd016be12016-03-13 11:24:20 -06001258 function->addParameter(param);
John Kessenich4678ca92016-05-13 09:33:42 -06001259 if (arguments)
1260 arguments = intermediate.growAggregate(arguments, newArg);
1261 else
1262 arguments = newArg;
John Kessenichd016be12016-03-13 11:24:20 -06001263}
1264
John Kessenichd21baed2016-09-16 03:05:12 -06001265// Some simple source assignments need to be flattened to a sequence
1266// of AST assignments. Catch these and flatten, otherwise, pass through
1267// to intermediate.addAssign().
John Kessenichf9115002016-09-18 23:10:22 -06001268TIntermTyped* HlslParseContext::handleAssign(const TSourceLoc& loc, TOperator op, TIntermTyped* left, TIntermTyped* right) const
John Kessenichd21baed2016-09-16 03:05:12 -06001269{
steve-lunarg90707962016-10-07 19:35:40 -06001270 if (left == nullptr || right == nullptr)
1271 return nullptr;
1272
John Kessenichd2ce8382016-09-16 19:44:00 -06001273 const auto mustFlatten = [&](const TIntermTyped& node) {
1274 return shouldFlatten(node.getType()) && node.getAsSymbolNode() &&
1275 flattenMap.find(node.getAsSymbolNode()->getId()) != flattenMap.end();
1276 };
1277
steve-lunarge0b9deb2016-09-16 13:26:37 -06001278 const bool flattenLeft = mustFlatten(*left);
1279 const bool flattenRight = mustFlatten(*right);
John Kessenichd2ce8382016-09-16 19:44:00 -06001280 if (! flattenLeft && ! flattenRight)
John Kessenichd21baed2016-09-16 03:05:12 -06001281 return intermediate.addAssign(op, left, right, loc);
1282
steve-lunarge0b9deb2016-09-16 13:26:37 -06001283 TIntermAggregate* assignList = nullptr;
John Kessenichf9115002016-09-18 23:10:22 -06001284 const TVector<TVariable*>* leftVariables = nullptr;
1285 const TVector<TVariable*>* rightVariables = nullptr;
steve-lunarge0b9deb2016-09-16 13:26:37 -06001286
steve-lunarg2199c242016-10-02 22:13:22 -06001287 // A temporary to store the right node's value, so we don't keep indirecting into it
1288 // if it's not a simple symbol.
1289 TVariable* rhsTempVar = nullptr;
1290
1291 // If the RHS is a simple symbol node, we'll copy it for each member.
1292 TIntermSymbol* cloneSymNode = nullptr;
1293
1294 // Array structs are not yet handled in flattening. (Compilation error upstream, so
1295 // this should never fire).
1296 assert(!(left->getType().isStruct() && left->getType().isArray()));
1297
1298 int memberCount = 0;
1299
1300 // Track how many items there are to copy.
1301 if (left->getType().isStruct())
Alex Szpakowski49ad2b72016-10-08 22:07:20 -03001302 memberCount = (int)left->getType().getStruct()->size();
steve-lunarg2199c242016-10-02 22:13:22 -06001303 if (left->getType().isArray())
1304 memberCount = left->getType().getCumulativeArraySize();
1305
John Kessenichfcea3022016-09-16 21:16:04 -06001306 if (flattenLeft)
John Kessenichf9115002016-09-18 23:10:22 -06001307 leftVariables = &flattenMap.find(left->getAsSymbolNode()->getId())->second;
steve-lunarg2199c242016-10-02 22:13:22 -06001308
1309 if (flattenRight) {
John Kessenichf9115002016-09-18 23:10:22 -06001310 rightVariables = &flattenMap.find(right->getAsSymbolNode()->getId())->second;
steve-lunarg2199c242016-10-02 22:13:22 -06001311 } else {
1312 // The RHS is not flattened. There are several cases:
1313 // 1. 1 item to copy: Use the RHS directly.
1314 // 2. >1 item, simple symbol RHS: we'll create a new TIntermSymbol node for each, but no assign to temp.
1315 // 3. >1 item, complex RHS: assign it to a new temp variable, and create a TIntermSymbol for each member.
1316
1317 if (memberCount <= 1) {
1318 // case 1: we'll use the symbol directly below. Nothing to do.
1319 } else {
1320 if (right->getAsSymbolNode() != nullptr) {
1321 // case 2: we'll copy the symbol per iteration below.
1322 cloneSymNode = right->getAsSymbolNode();
1323 } else {
1324 // case 3: assign to a temp, and indirect into that.
1325 rhsTempVar = makeInternalVariable("flattenTemp", right->getType());
1326 rhsTempVar->getWritableType().getQualifier().makeTemporary();
1327 TIntermTyped* noFlattenRHS = intermediate.addSymbol(*rhsTempVar, loc);
1328
1329 // Add this to the aggregate being built.
1330 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, noFlattenRHS, right, loc), loc);
1331 }
1332 }
1333 }
steve-lunarge0b9deb2016-09-16 13:26:37 -06001334
1335 const auto getMember = [&](bool flatten, TIntermTyped* node,
1336 const TVector<TVariable*>& memberVariables, int member,
1337 TOperator op, const TType& memberType) {
1338 TIntermTyped* subTree;
1339 if (flatten)
1340 subTree = intermediate.addSymbol(*memberVariables[member]);
1341 else {
1342 subTree = intermediate.addIndex(op, node, intermediate.addConstantUnion(member, loc), loc);
1343 subTree->setType(memberType);
1344 }
1345
1346 return subTree;
1347 };
1348
steve-lunarg2199c242016-10-02 22:13:22 -06001349 // Return the proper RHS node: a new symbol from a TVariable, copy
1350 // of an TIntermSymbol node, or sometimes the right node directly.
1351 const auto getRHS = [&]() {
1352 return rhsTempVar ? intermediate.addSymbol(*rhsTempVar, loc) :
1353 cloneSymNode ? intermediate.addSymbol(*cloneSymNode) :
1354 right;
1355 };
1356
steve-lunarge0b9deb2016-09-16 13:26:37 -06001357 // Handle struct assignment
1358 if (left->getType().isStruct()) {
1359 // If we get here, we are assigning to or from a whole struct that must be
1360 // flattened, so have to do member-by-member assignment:
1361 const auto& members = *left->getType().getStruct();
1362
1363 for (int member = 0; member < (int)members.size(); ++member) {
steve-lunarg2199c242016-10-02 22:13:22 -06001364 TIntermTyped* subRight = getMember(flattenRight, getRHS(), *rightVariables, member,
steve-lunarge0b9deb2016-09-16 13:26:37 -06001365 EOpIndexDirectStruct, *members[member].type);
1366 TIntermTyped* subLeft = getMember(flattenLeft, left, *leftVariables, member,
1367 EOpIndexDirectStruct, *members[member].type);
John Kessenicha08c9292016-10-01 17:17:55 -06001368 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, subLeft, subRight, loc), loc);
steve-lunarge0b9deb2016-09-16 13:26:37 -06001369 }
John Kessenichd21baed2016-09-16 03:05:12 -06001370 }
steve-lunarge0b9deb2016-09-16 13:26:37 -06001371
1372 // Handle array assignment
1373 if (left->getType().isArray()) {
1374 // If we get here, we are assigning to or from a whole array that must be
1375 // flattened, so have to do member-by-member assignment:
1376
1377 const TType dereferencedType(left->getType(), 0);
steve-lunarge0b9deb2016-09-16 13:26:37 -06001378
steve-lunarg2199c242016-10-02 22:13:22 -06001379 for (int element=0; element < memberCount; ++element) {
1380 // Add a new AST symbol node if we have a temp variable holding a complex RHS.
1381 TIntermTyped* subRight = getMember(flattenRight, getRHS(), *rightVariables, element,
steve-lunarge0b9deb2016-09-16 13:26:37 -06001382 EOpIndexDirect, dereferencedType);
1383 TIntermTyped* subLeft = getMember(flattenLeft, left, *leftVariables, element,
1384 EOpIndexDirect, dereferencedType);
1385
John Kessenicha08c9292016-10-01 17:17:55 -06001386 assignList = intermediate.growAggregate(assignList, intermediate.addAssign(op, subLeft, subRight, loc), loc);
steve-lunarge0b9deb2016-09-16 13:26:37 -06001387 }
1388 }
1389
1390 assert(assignList != nullptr);
John Kessenichd21baed2016-09-16 03:05:12 -06001391 assignList->setOperator(EOpSequence);
1392
1393 return assignList;
1394}
1395
LoopDawg58910702016-06-13 09:22:28 -06001396//
1397// HLSL atomic operations have slightly different arguments than
1398// GLSL/AST/SPIRV. The semantics are converted below in decomposeIntrinsic.
1399// This provides the post-decomposition equivalent opcode.
1400//
1401TOperator HlslParseContext::mapAtomicOp(const TSourceLoc& loc, TOperator op, bool isImage)
1402{
1403 switch (op) {
1404 case EOpInterlockedAdd: return isImage ? EOpImageAtomicAdd : EOpAtomicAdd;
1405 case EOpInterlockedAnd: return isImage ? EOpImageAtomicAnd : EOpAtomicAnd;
1406 case EOpInterlockedCompareExchange: return isImage ? EOpImageAtomicCompSwap : EOpAtomicCompSwap;
1407 case EOpInterlockedMax: return isImage ? EOpImageAtomicMax : EOpAtomicMax;
1408 case EOpInterlockedMin: return isImage ? EOpImageAtomicMin : EOpAtomicMin;
1409 case EOpInterlockedOr: return isImage ? EOpImageAtomicOr : EOpAtomicOr;
1410 case EOpInterlockedXor: return isImage ? EOpImageAtomicXor : EOpAtomicXor;
1411 case EOpInterlockedExchange: return isImage ? EOpImageAtomicExchange : EOpAtomicExchange;
1412 case EOpInterlockedCompareStore: // TODO: ...
1413 default:
1414 error(loc, "unknown atomic operation", "unknown op", "");
1415 return EOpNull;
1416 }
1417}
1418
LoopDawg4624a022016-06-20 13:26:59 -06001419//
LoopDawga2b79912016-07-14 14:45:14 -06001420// Create a combined sampler/texture from separate sampler and texture.
LoopDawg4624a022016-06-20 13:26:59 -06001421//
LoopDawga2b79912016-07-14 14:45:14 -06001422TIntermAggregate* HlslParseContext::handleSamplerTextureCombine(const TSourceLoc& loc, TIntermTyped* argTex, TIntermTyped* argSampler)
1423{
1424 TIntermAggregate* txcombine = new TIntermAggregate(EOpConstructTextureSampler);
1425
1426 txcombine->getSequence().push_back(argTex);
1427 txcombine->getSequence().push_back(argSampler);
1428
1429 TSampler samplerType = argTex->getType().getSampler();
1430 samplerType.combined = true;
LoopDawga78b0292016-07-19 14:28:05 -06001431 samplerType.shadow = argSampler->getType().getSampler().shadow;
LoopDawga2b79912016-07-14 14:45:14 -06001432
1433 txcombine->setType(TType(samplerType, EvqTemporary));
1434 txcombine->setLoc(loc);
1435
1436 return txcombine;
1437}
1438
1439//
1440// Decompose DX9 and DX10 sample intrinsics & object methods into AST
1441//
1442void HlslParseContext::decomposeSampleMethods(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
LoopDawg4624a022016-06-20 13:26:59 -06001443{
1444 if (!node || !node->getAsOperator())
1445 return;
1446
1447 const TOperator op = node->getAsOperator()->getOp();
1448 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
1449
1450 switch (op) {
LoopDawga2b79912016-07-14 14:45:14 -06001451 // **** DX9 intrinsics: ****
LoopDawg4624a022016-06-20 13:26:59 -06001452 case EOpTexture:
1453 {
LoopDawga2b79912016-07-14 14:45:14 -06001454 // Texture with ddx & ddy is really gradient form in HLSL
LoopDawg4624a022016-06-20 13:26:59 -06001455 if (argAggregate->getSequence().size() == 4) {
1456 node->getAsAggregate()->setOperator(EOpTextureGrad);
1457 break;
1458 }
1459
1460 break;
1461 }
1462
1463 case EOpTextureBias:
1464 {
1465 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // sampler
1466 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // coord
1467
1468 // HLSL puts bias in W component of coordinate. We extract it and add it to
1469 // the argument list, instead
1470 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
1471 TIntermTyped* bias = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
1472
1473 TOperator constructOp = EOpNull;
1474 switch (arg0->getType().getSampler().dim) {
1475 case Esd1D: constructOp = EOpConstructFloat; break; // 1D
1476 case Esd2D: constructOp = EOpConstructVec2; break; // 2D
1477 case Esd3D: constructOp = EOpConstructVec3; break; // 3D
1478 case EsdCube: constructOp = EOpConstructVec3; break; // also 3D
1479 default: break;
1480 }
1481
1482 TIntermAggregate* constructCoord = new TIntermAggregate(constructOp);
1483 constructCoord->getSequence().push_back(arg1);
1484 constructCoord->setLoc(loc);
1485
1486 TIntermAggregate* tex = new TIntermAggregate(EOpTexture);
1487 tex->getSequence().push_back(arg0); // sampler
1488 tex->getSequence().push_back(constructCoord); // coordinate
1489 tex->getSequence().push_back(bias); // bias
1490 tex->setLoc(loc);
1491 node = tex;
1492
1493 break;
1494 }
1495
LoopDawga2b79912016-07-14 14:45:14 -06001496 // **** DX10 methods: ****
1497 case EOpMethodSample: // fall through
1498 case EOpMethodSampleBias: // ...
1499 {
1500 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1501 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
1502 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
1503 TIntermTyped* argBias = nullptr;
1504 TIntermTyped* argOffset = nullptr;
1505
1506 int nextArg = 3;
1507
1508 if (op == EOpMethodSampleBias) // SampleBias has a bias arg
1509 argBias = argAggregate->getSequence()[nextArg++]->getAsTyped();
1510
1511 TOperator textureOp = EOpTexture;
1512
John Kesseniche4821e42016-07-16 10:19:43 -06001513 if ((int)argAggregate->getSequence().size() == (nextArg+1)) { // last parameter is offset form
LoopDawga2b79912016-07-14 14:45:14 -06001514 textureOp = EOpTextureOffset;
1515 argOffset = argAggregate->getSequence()[nextArg++]->getAsTyped();
1516 }
1517
1518 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1519
1520 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
1521 txsample->getSequence().push_back(txcombine);
1522 txsample->getSequence().push_back(argCoord);
1523
1524 if (argBias != nullptr)
1525 txsample->getSequence().push_back(argBias);
1526
1527 if (argOffset != nullptr)
1528 txsample->getSequence().push_back(argOffset);
1529
1530 txsample->setType(node->getType());
1531 txsample->setLoc(loc);
1532 node = txsample;
1533
1534 break;
1535 }
1536
1537 case EOpMethodSampleGrad: // ...
1538 {
1539 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1540 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
1541 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
1542 TIntermTyped* argDDX = argAggregate->getSequence()[3]->getAsTyped();
1543 TIntermTyped* argDDY = argAggregate->getSequence()[4]->getAsTyped();
1544 TIntermTyped* argOffset = nullptr;
1545
1546 TOperator textureOp = EOpTextureGrad;
1547
1548 if (argAggregate->getSequence().size() == 6) { // last parameter is offset form
1549 textureOp = EOpTextureGradOffset;
1550 argOffset = argAggregate->getSequence()[5]->getAsTyped();
1551 }
1552
1553 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1554
1555 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
1556 txsample->getSequence().push_back(txcombine);
1557 txsample->getSequence().push_back(argCoord);
1558 txsample->getSequence().push_back(argDDX);
1559 txsample->getSequence().push_back(argDDY);
1560
1561 if (argOffset != nullptr)
1562 txsample->getSequence().push_back(argOffset);
1563
1564 txsample->setType(node->getType());
1565 txsample->setLoc(loc);
1566 node = txsample;
1567
1568 break;
1569 }
1570
LoopDawg5d58fae2016-07-15 11:22:24 -06001571 case EOpMethodGetDimensions:
1572 {
1573 // AST returns a vector of results, which we break apart component-wise into
1574 // separate values to assign to the HLSL method's outputs, ala:
1575 // tx . GetDimensions(width, height);
1576 // float2 sizeQueryTemp = EOpTextureQuerySize
1577 // width = sizeQueryTemp.X;
1578 // height = sizeQueryTemp.Y;
1579
1580 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1581 const TType& texType = argTex->getType();
1582
1583 assert(texType.getBasicType() == EbtSampler);
1584
1585 const TSampler& texSampler = texType.getSampler();
1586 const TSamplerDim dim = texSampler.dim;
steve-lunargbb0183f2016-10-04 16:58:14 -06001587 const bool isImage = texSampler.isImage();
John Kessenich267590d2016-08-05 17:34:34 -06001588 const int numArgs = (int)argAggregate->getSequence().size();
LoopDawg5d58fae2016-07-15 11:22:24 -06001589
1590 int numDims = 0;
1591
1592 switch (dim) {
steve-lunargbb0183f2016-10-04 16:58:14 -06001593 case Esd1D: numDims = 1; break; // W
1594 case Esd2D: numDims = 2; break; // W, H
1595 case Esd3D: numDims = 3; break; // W, H, D
1596 case EsdCube: numDims = 2; break; // W, H (cube)
steve-lunarg6b43d272016-10-06 20:12:24 -06001597 case EsdBuffer: numDims = 1; break; // W (buffers)
LoopDawg5d58fae2016-07-15 11:22:24 -06001598 default:
1599 assert(0 && "unhandled texture dimension");
1600 }
1601
1602 // Arrayed adds another dimension for the number of array elements
1603 if (texSampler.isArrayed())
1604 ++numDims;
1605
1606 // Establish whether we're querying mip levels
steve-lunarg1e19d902016-07-26 15:19:28 -06001607 const bool mipQuery = (numArgs > (numDims + 1)) && (!texSampler.isMultiSample());
LoopDawg5d58fae2016-07-15 11:22:24 -06001608
1609 // AST assumes integer return. Will be converted to float if required.
steve-lunargbb0183f2016-10-04 16:58:14 -06001610 TIntermAggregate* sizeQuery = new TIntermAggregate(isImage ? EOpImageQuerySize : EOpTextureQuerySize);
LoopDawg5d58fae2016-07-15 11:22:24 -06001611 sizeQuery->getSequence().push_back(argTex);
1612 // If we're querying an explicit LOD, add the LOD, which is always arg #1
1613 if (mipQuery) {
1614 TIntermTyped* queryLod = argAggregate->getSequence()[1]->getAsTyped();
1615 sizeQuery->getSequence().push_back(queryLod);
1616 }
1617 sizeQuery->setType(TType(EbtUint, EvqTemporary, numDims));
1618 sizeQuery->setLoc(loc);
1619
1620 // Return value from size query
1621 TVariable* tempArg = makeInternalVariable("sizeQueryTemp", sizeQuery->getType());
1622 tempArg->getWritableType().getQualifier().makeTemporary();
steve-lunarg2199c242016-10-02 22:13:22 -06001623 TIntermTyped* sizeQueryAssign = intermediate.addAssign(EOpAssign,
1624 intermediate.addSymbol(*tempArg, loc),
1625 sizeQuery, loc);
LoopDawg5d58fae2016-07-15 11:22:24 -06001626
1627 // Compound statement for assigning outputs
1628 TIntermAggregate* compoundStatement = intermediate.makeAggregate(sizeQueryAssign, loc);
1629 // Index of first output parameter
1630 const int outParamBase = mipQuery ? 2 : 1;
1631
1632 for (int compNum = 0; compNum < numDims; ++compNum) {
1633 TIntermTyped* indexedOut = nullptr;
steve-lunarg2199c242016-10-02 22:13:22 -06001634 TIntermSymbol* sizeQueryReturn = intermediate.addSymbol(*tempArg, loc);
LoopDawg5d58fae2016-07-15 11:22:24 -06001635
1636 if (numDims > 1) {
1637 TIntermTyped* component = intermediate.addConstantUnion(compNum, loc, true);
1638 indexedOut = intermediate.addIndex(EOpIndexDirect, sizeQueryReturn, component, loc);
1639 indexedOut->setType(TType(EbtUint, EvqTemporary, 1));
1640 indexedOut->setLoc(loc);
1641 } else {
1642 indexedOut = sizeQueryReturn;
1643 }
1644
1645 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + compNum]->getAsTyped();
1646 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, indexedOut, loc);
1647
1648 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
1649 }
1650
1651 // handle mip level parameter
1652 if (mipQuery) {
1653 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
1654
1655 TIntermAggregate* levelsQuery = new TIntermAggregate(EOpTextureQueryLevels);
1656 levelsQuery->getSequence().push_back(argTex);
1657 levelsQuery->setType(TType(EbtUint, EvqTemporary, 1));
1658 levelsQuery->setLoc(loc);
1659
1660 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, levelsQuery, loc);
1661 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
1662 }
1663
steve-lunarg1e19d902016-07-26 15:19:28 -06001664 // 2DMS formats query # samples, which needs a different query op
1665 if (texSampler.isMultiSample()) {
1666 TIntermTyped* outParam = argAggregate->getSequence()[outParamBase + numDims]->getAsTyped();
1667
1668 TIntermAggregate* samplesQuery = new TIntermAggregate(EOpImageQuerySamples);
1669 samplesQuery->getSequence().push_back(argTex);
1670 samplesQuery->setType(TType(EbtUint, EvqTemporary, 1));
1671 samplesQuery->setLoc(loc);
1672
1673 TIntermTyped* compAssign = intermediate.addAssign(EOpAssign, outParam, samplesQuery, loc);
1674 compoundStatement = intermediate.growAggregate(compoundStatement, compAssign);
1675 }
1676
LoopDawg5d58fae2016-07-15 11:22:24 -06001677 compoundStatement->setOperator(EOpSequence);
1678 compoundStatement->setLoc(loc);
1679 compoundStatement->setType(TType(EbtVoid));
1680
1681 node = compoundStatement;
1682
1683 break;
1684 }
1685
LoopDawga78b0292016-07-19 14:28:05 -06001686 case EOpMethodSampleCmp: // fall through...
1687 case EOpMethodSampleCmpLevelZero:
1688 {
1689 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1690 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
1691 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
1692 TIntermTyped* argCmpVal = argAggregate->getSequence()[3]->getAsTyped();
1693 TIntermTyped* argOffset = nullptr;
1694
1695 // optional offset value
1696 if (argAggregate->getSequence().size() > 4)
1697 argOffset = argAggregate->getSequence()[4]->getAsTyped();
1698
1699 const int coordDimWithCmpVal = argCoord->getType().getVectorSize() + 1; // +1 for cmp
1700
1701 // AST wants comparison value as one of the texture coordinates
1702 TOperator constructOp = EOpNull;
1703 switch (coordDimWithCmpVal) {
1704 // 1D can't happen: there's always at least 1 coordinate dimension + 1 cmp val
1705 case 2: constructOp = EOpConstructVec2; break;
1706 case 3: constructOp = EOpConstructVec3; break;
1707 case 4: constructOp = EOpConstructVec4; break;
1708 case 5: constructOp = EOpConstructVec4; break; // cubeArrayShadow, cmp value is separate arg.
1709 default: assert(0); break;
1710 }
1711
1712 TIntermAggregate* coordWithCmp = new TIntermAggregate(constructOp);
1713 coordWithCmp->getSequence().push_back(argCoord);
1714 if (coordDimWithCmpVal != 5) // cube array shadow is special.
1715 coordWithCmp->getSequence().push_back(argCmpVal);
1716 coordWithCmp->setLoc(loc);
1717
1718 TOperator textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLod : EOpTexture);
1719 if (argOffset != nullptr)
1720 textureOp = (op == EOpMethodSampleCmpLevelZero ? EOpTextureLodOffset : EOpTextureOffset);
1721
1722 // Create combined sampler & texture op
1723 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1724 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
1725 txsample->getSequence().push_back(txcombine);
1726 txsample->getSequence().push_back(coordWithCmp);
1727
1728 if (coordDimWithCmpVal == 5) // cube array shadow is special: cmp val follows coord.
1729 txsample->getSequence().push_back(argCmpVal);
1730
1731 // the LevelZero form uses 0 as an explicit LOD
1732 if (op == EOpMethodSampleCmpLevelZero)
1733 txsample->getSequence().push_back(intermediate.addConstantUnion(0.0, EbtFloat, loc, true));
1734
1735 // Add offset if present
1736 if (argOffset != nullptr)
1737 txsample->getSequence().push_back(argOffset);
1738
1739 txsample->setType(node->getType());
1740 txsample->setLoc(loc);
1741 node = txsample;
1742
1743 break;
1744 }
1745
LoopDawgf2451012016-07-20 16:34:44 -06001746 case EOpMethodLoad:
1747 {
1748 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1749 TIntermTyped* argCoord = argAggregate->getSequence()[1]->getAsTyped();
1750 TIntermTyped* argOffset = nullptr;
1751 TIntermTyped* lodComponent = nullptr;
1752 TIntermTyped* coordSwizzle = nullptr;
1753
1754 const bool isMS = argTex->getType().getSampler().isMultiSample();
steve-lunargd53f7172016-07-27 15:46:48 -06001755 const bool isBuffer = argTex->getType().getSampler().dim == EsdBuffer;
steve-lunargbb0183f2016-10-04 16:58:14 -06001756 const bool isImage = argTex->getType().getSampler().isImage();
LoopDawgf2451012016-07-20 16:34:44 -06001757 const TBasicType coordBaseType = argCoord->getType().getBasicType();
1758
1759 // Last component of coordinate is the mip level, for non-MS. we separate them here:
steve-lunargbb0183f2016-10-04 16:58:14 -06001760 if (isMS || isBuffer || isImage) {
1761 // MS, Buffer, and Image have no LOD
steve-lunarg1e19d902016-07-26 15:19:28 -06001762 coordSwizzle = argCoord;
LoopDawgf2451012016-07-20 16:34:44 -06001763 } else {
1764 // Extract coordinate
1765 TVectorFields coordFields(0,1,2,3);
1766 coordFields.num = argCoord->getType().getVectorSize() - (isMS ? 0 : 1);
1767 TIntermTyped* coordIdx = intermediate.addSwizzle(coordFields, loc);
1768 coordSwizzle = intermediate.addIndex(EOpVectorSwizzle, argCoord, coordIdx, loc);
1769 coordSwizzle->setType(TType(coordBaseType, EvqTemporary, coordFields.num));
1770
1771 // Extract LOD
1772 TIntermTyped* lodIdx = intermediate.addConstantUnion(coordFields.num, loc, true);
1773 lodComponent = intermediate.addIndex(EOpIndexDirect, argCoord, lodIdx, loc);
1774 lodComponent->setType(TType(coordBaseType, EvqTemporary, 1));
1775 }
1776
John Kessenich267590d2016-08-05 17:34:34 -06001777 const int numArgs = (int)argAggregate->getSequence().size();
LoopDawgf2451012016-07-20 16:34:44 -06001778 const bool hasOffset = ((!isMS && numArgs == 3) || (isMS && numArgs == 4));
1779
LoopDawgf2451012016-07-20 16:34:44 -06001780 // Create texel fetch
steve-lunargbb0183f2016-10-04 16:58:14 -06001781 const TOperator fetchOp = (isImage ? EOpImageLoad :
1782 hasOffset ? EOpTextureFetchOffset :
1783 EOpTextureFetch);
LoopDawgf2451012016-07-20 16:34:44 -06001784 TIntermAggregate* txfetch = new TIntermAggregate(fetchOp);
1785
LoopDawgf2451012016-07-20 16:34:44 -06001786 // Build up the fetch
1787 txfetch->getSequence().push_back(argTex);
1788 txfetch->getSequence().push_back(coordSwizzle);
1789
steve-lunarg1e19d902016-07-26 15:19:28 -06001790 if (isMS) {
1791 // add 2DMS sample index
1792 TIntermTyped* argSampleIdx = argAggregate->getSequence()[2]->getAsTyped();
1793 txfetch->getSequence().push_back(argSampleIdx);
steve-lunargd53f7172016-07-27 15:46:48 -06001794 } else if (isBuffer) {
1795 // Nothing else to do for buffers.
steve-lunargbb0183f2016-10-04 16:58:14 -06001796 } else if (isImage) {
1797 // Nothing else to do for images.
steve-lunarg1e19d902016-07-26 15:19:28 -06001798 } else {
steve-lunargd53f7172016-07-27 15:46:48 -06001799 // 2DMS and buffer have no LOD, but everything else does.
LoopDawgf2451012016-07-20 16:34:44 -06001800 txfetch->getSequence().push_back(lodComponent);
steve-lunarg1e19d902016-07-26 15:19:28 -06001801 }
LoopDawgf2451012016-07-20 16:34:44 -06001802
steve-lunarg1e19d902016-07-26 15:19:28 -06001803 // Obtain offset arg, if there is one.
1804 if (hasOffset) {
1805 const int offsetPos = (isMS ? 3 : 2);
1806 argOffset = argAggregate->getSequence()[offsetPos]->getAsTyped();
LoopDawgf2451012016-07-20 16:34:44 -06001807 txfetch->getSequence().push_back(argOffset);
steve-lunarg1e19d902016-07-26 15:19:28 -06001808 }
LoopDawgf2451012016-07-20 16:34:44 -06001809
steve-lunarg4f2da272016-10-10 15:24:57 -06001810 int vecSize = TQualifier::getLayoutComponentCount(argTex->getType().getQualifier().layoutFormat);
1811
1812 txfetch->setType(TType(node->getType().getBasicType(), EvqTemporary, vecSize));
LoopDawgf2451012016-07-20 16:34:44 -06001813 txfetch->setLoc(loc);
1814 node = txfetch;
1815
1816 break;
1817 }
1818
LoopDawg3ef78522016-07-21 15:02:16 -06001819 case EOpMethodSampleLevel:
1820 {
1821 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1822 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
1823 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
1824 TIntermTyped* argLod = argAggregate->getSequence()[3]->getAsTyped();
1825 TIntermTyped* argOffset = nullptr;
1826
John Kessenich267590d2016-08-05 17:34:34 -06001827 const int numArgs = (int)argAggregate->getSequence().size();
LoopDawg3ef78522016-07-21 15:02:16 -06001828
1829 if (numArgs == 5) // offset, if present
1830 argOffset = argAggregate->getSequence()[4]->getAsTyped();
1831
1832 const TOperator textureOp = (argOffset == nullptr ? EOpTextureLod : EOpTextureLodOffset);
1833 TIntermAggregate* txsample = new TIntermAggregate(textureOp);
1834
1835 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1836
1837 txsample->getSequence().push_back(txcombine);
1838 txsample->getSequence().push_back(argCoord);
1839 txsample->getSequence().push_back(argLod);
1840
1841 if (argOffset != nullptr)
1842 txsample->getSequence().push_back(argOffset);
1843
1844 txsample->setType(node->getType());
1845 txsample->setLoc(loc);
1846 node = txsample;
1847
1848 break;
1849 }
1850
LoopDawga2f3d282016-07-22 08:28:11 -06001851 case EOpMethodGather:
1852 {
1853 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
1854 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
1855 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
1856 TIntermTyped* argOffset = nullptr;
1857
1858 // Offset is optional
steve-lunarg7dfcf4d2016-07-31 10:37:02 -06001859 if (argAggregate->getSequence().size() > 3)
LoopDawga2f3d282016-07-22 08:28:11 -06001860 argOffset = argAggregate->getSequence()[3]->getAsTyped();
1861
1862 const TOperator textureOp = (argOffset == nullptr ? EOpTextureGather : EOpTextureGatherOffset);
1863 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
1864
1865 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1866
1867 txgather->getSequence().push_back(txcombine);
1868 txgather->getSequence().push_back(argCoord);
steve-lunarg7dfcf4d2016-07-31 10:37:02 -06001869 // Offset if not given is implicitly channel 0 (red)
LoopDawga2f3d282016-07-22 08:28:11 -06001870
1871 if (argOffset != nullptr)
1872 txgather->getSequence().push_back(argOffset);
1873
1874 txgather->setType(node->getType());
1875 txgather->setLoc(loc);
1876 node = txgather;
1877
1878 break;
1879 }
1880
steve-lunarg7dfcf4d2016-07-31 10:37:02 -06001881 case EOpMethodGatherRed: // fall through...
1882 case EOpMethodGatherGreen: // ...
1883 case EOpMethodGatherBlue: // ...
1884 case EOpMethodGatherAlpha: // ...
1885 case EOpMethodGatherCmpRed: // ...
1886 case EOpMethodGatherCmpGreen: // ...
1887 case EOpMethodGatherCmpBlue: // ...
1888 case EOpMethodGatherCmpAlpha: // ...
1889 {
1890 int channel = 0; // the channel we are gathering
1891 int cmpValues = 0; // 1 if there is a compare value (handier than a bool below)
1892
1893 switch (op) {
1894 case EOpMethodGatherCmpRed: cmpValues = 1; // fall through
1895 case EOpMethodGatherRed: channel = 0; break;
1896 case EOpMethodGatherCmpGreen: cmpValues = 1; // fall through
1897 case EOpMethodGatherGreen: channel = 1; break;
1898 case EOpMethodGatherCmpBlue: cmpValues = 1; // fall through
1899 case EOpMethodGatherBlue: channel = 2; break;
1900 case EOpMethodGatherCmpAlpha: cmpValues = 1; // fall through
1901 case EOpMethodGatherAlpha: channel = 3; break;
1902 default: assert(0); break;
1903 }
1904
1905 // For now, we have nothing to map the component-wise comparison forms
1906 // to, because neither GLSL nor SPIR-V has such an opcode. Issue an
1907 // unimplemented error instead. Most of the machinery is here if that
1908 // should ever become available.
1909 if (cmpValues) {
1910 error(loc, "unimplemented: component-level gather compare", "", "");
1911 return;
1912 }
1913
1914 int arg = 0;
1915
1916 TIntermTyped* argTex = argAggregate->getSequence()[arg++]->getAsTyped();
1917 TIntermTyped* argSamp = argAggregate->getSequence()[arg++]->getAsTyped();
1918 TIntermTyped* argCoord = argAggregate->getSequence()[arg++]->getAsTyped();
1919 TIntermTyped* argOffset = nullptr;
1920 TIntermTyped* argOffsets[4] = { nullptr, nullptr, nullptr, nullptr };
1921 // TIntermTyped* argStatus = nullptr; // TODO: residency
1922 TIntermTyped* argCmp = nullptr;
1923
1924 const TSamplerDim dim = argTex->getType().getSampler().dim;
1925
baldurk1eb1c112016-08-15 18:01:15 +02001926 const int argSize = (int)argAggregate->getSequence().size();
steve-lunarg7dfcf4d2016-07-31 10:37:02 -06001927 bool hasStatus = (argSize == (5+cmpValues) || argSize == (8+cmpValues));
1928 bool hasOffset1 = false;
1929 bool hasOffset4 = false;
1930
1931 // Only 2D forms can have offsets. Discover if we have 0, 1 or 4 offsets.
1932 if (dim == Esd2D) {
1933 hasOffset1 = (argSize == (4+cmpValues) || argSize == (5+cmpValues));
1934 hasOffset4 = (argSize == (7+cmpValues) || argSize == (8+cmpValues));
1935 }
1936
1937 assert(!(hasOffset1 && hasOffset4));
1938
1939 TOperator textureOp = EOpTextureGather;
1940
1941 // Compare forms have compare value
1942 if (cmpValues != 0)
1943 argCmp = argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
1944
1945 // Some forms have single offset
1946 if (hasOffset1) {
1947 textureOp = EOpTextureGatherOffset; // single offset form
1948 argOffset = argAggregate->getSequence()[arg++]->getAsTyped();
1949 }
1950
1951 // Some forms have 4 gather offsets
1952 if (hasOffset4) {
1953 textureOp = EOpTextureGatherOffsets; // note plural, for 4 offset form
1954 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
1955 argOffsets[offsetNum] = argAggregate->getSequence()[arg++]->getAsTyped();
1956 }
1957
1958 // Residency status
1959 if (hasStatus) {
1960 // argStatus = argAggregate->getSequence()[arg++]->getAsTyped();
1961 error(loc, "unimplemented: residency status", "", "");
1962 return;
1963 }
1964
1965 TIntermAggregate* txgather = new TIntermAggregate(textureOp);
1966 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
1967
1968 TIntermTyped* argChannel = intermediate.addConstantUnion(channel, loc, true);
1969
1970 txgather->getSequence().push_back(txcombine);
1971 txgather->getSequence().push_back(argCoord);
1972
1973 // AST wants an array of 4 offsets, where HLSL has separate args. Here
1974 // we construct an array from the separate args.
1975 if (hasOffset4) {
1976 TType arrayType(EbtInt, EvqTemporary, 2);
1977 TArraySizes arraySizes;
1978 arraySizes.addInnerSize(4);
1979 arrayType.newArraySizes(arraySizes);
1980
1981 TIntermAggregate* initList = new TIntermAggregate(EOpNull);
1982
1983 for (int offsetNum = 0; offsetNum < 4; ++offsetNum)
1984 initList->getSequence().push_back(argOffsets[offsetNum]);
1985
1986 argOffset = addConstructor(loc, initList, arrayType);
1987 }
1988
1989 // Add comparison value if we have one
1990 if (argTex->getType().getSampler().isShadow())
1991 txgather->getSequence().push_back(argCmp);
1992
1993 // Add offset (either 1, or an array of 4) if we have one
1994 if (argOffset != nullptr)
1995 txgather->getSequence().push_back(argOffset);
1996
1997 txgather->getSequence().push_back(argChannel);
1998
1999 txgather->setType(node->getType());
2000 txgather->setLoc(loc);
2001 node = txgather;
2002
2003 break;
2004 }
2005
steve-lunarg68f2c142016-07-26 08:57:53 -06002006 case EOpMethodCalculateLevelOfDetail:
2007 case EOpMethodCalculateLevelOfDetailUnclamped:
2008 {
2009 TIntermTyped* argTex = argAggregate->getSequence()[0]->getAsTyped();
2010 TIntermTyped* argSamp = argAggregate->getSequence()[1]->getAsTyped();
2011 TIntermTyped* argCoord = argAggregate->getSequence()[2]->getAsTyped();
2012
2013 TIntermAggregate* txquerylod = new TIntermAggregate(EOpTextureQueryLod);
2014
2015 TIntermAggregate* txcombine = handleSamplerTextureCombine(loc, argTex, argSamp);
2016 txquerylod->getSequence().push_back(txcombine);
2017 txquerylod->getSequence().push_back(argCoord);
2018
2019 TIntermTyped* lodComponent = intermediate.addConstantUnion(0, loc, true);
2020 TIntermTyped* lodComponentIdx = intermediate.addIndex(EOpIndexDirect, txquerylod, lodComponent, loc);
2021 lodComponentIdx->setType(TType(EbtFloat, EvqTemporary, 1));
2022
2023 node = lodComponentIdx;
2024
2025 // We cannot currently obtain the unclamped LOD
2026 if (op == EOpMethodCalculateLevelOfDetailUnclamped)
2027 error(loc, "unimplemented: CalculateLevelOfDetailUnclamped", "", "");
2028
2029 break;
2030 }
2031
2032 case EOpMethodGetSamplePosition:
2033 {
2034 error(loc, "unimplemented: GetSamplePosition", "", "");
2035 break;
2036 }
2037
LoopDawg4624a022016-06-20 13:26:59 -06002038 default:
2039 break; // most pass through unchanged
2040 }
2041}
2042
2043//
LoopDawg592860c2016-06-09 08:57:35 -06002044// Optionally decompose intrinsics to AST opcodes.
2045//
2046void HlslParseContext::decomposeIntrinsic(const TSourceLoc& loc, TIntermTyped*& node, TIntermNode* arguments)
2047{
2048 // HLSL intrinsics can be pass through to native AST opcodes, or decomposed here to existing AST
2049 // opcodes for compatibility with existing software stacks.
2050 static const bool decomposeHlslIntrinsics = true;
2051
2052 if (!decomposeHlslIntrinsics || !node || !node->getAsOperator())
2053 return;
2054
2055 const TIntermAggregate* argAggregate = arguments ? arguments->getAsAggregate() : nullptr;
2056 TIntermUnary* fnUnary = node->getAsUnaryNode();
2057 const TOperator op = node->getAsOperator()->getOp();
2058
2059 switch (op) {
2060 case EOpGenMul:
2061 {
2062 // mul(a,b) -> MatrixTimesMatrix, MatrixTimesVector, MatrixTimesScalar, VectorTimesScalar, Dot, Mul
steve-lunarg297ae212016-08-24 14:36:13 -06002063 // Since we are treating HLSL rows like GLSL columns (the first matrix indirection),
2064 // we must reverse the operand order here. Hence, arg0 gets sequence[1], etc.
2065 TIntermTyped* arg0 = argAggregate->getSequence()[1]->getAsTyped();
2066 TIntermTyped* arg1 = argAggregate->getSequence()[0]->getAsTyped();
LoopDawg592860c2016-06-09 08:57:35 -06002067
2068 if (arg0->isVector() && arg1->isVector()) { // vec * vec
2069 node->getAsAggregate()->setOperator(EOpDot);
2070 } else {
2071 node = handleBinaryMath(loc, "mul", EOpMul, arg0, arg1);
2072 }
2073
2074 break;
2075 }
2076
2077 case EOpRcp:
2078 {
2079 // rcp(a) -> 1 / a
2080 TIntermTyped* arg0 = fnUnary->getOperand();
2081 TBasicType type0 = arg0->getBasicType();
2082 TIntermTyped* one = intermediate.addConstantUnion(1, type0, loc, true);
2083 node = handleBinaryMath(loc, "rcp", EOpDiv, one, arg0);
2084
2085 break;
2086 }
2087
2088 case EOpSaturate:
2089 {
2090 // saturate(a) -> clamp(a,0,1)
2091 TIntermTyped* arg0 = fnUnary->getOperand();
2092 TBasicType type0 = arg0->getBasicType();
2093 TIntermAggregate* clamp = new TIntermAggregate(EOpClamp);
2094
2095 clamp->getSequence().push_back(arg0);
2096 clamp->getSequence().push_back(intermediate.addConstantUnion(0, type0, loc, true));
2097 clamp->getSequence().push_back(intermediate.addConstantUnion(1, type0, loc, true));
2098 clamp->setLoc(loc);
2099 clamp->setType(node->getType());
LoopDawg58910702016-06-13 09:22:28 -06002100 clamp->getWritableType().getQualifier().makeTemporary();
LoopDawg592860c2016-06-09 08:57:35 -06002101 node = clamp;
2102
2103 break;
2104 }
2105
2106 case EOpSinCos:
2107 {
2108 // sincos(a,b,c) -> b = sin(a), c = cos(a)
2109 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
2110 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
2111 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
2112
2113 TIntermTyped* sinStatement = handleUnaryMath(loc, "sin", EOpSin, arg0);
2114 TIntermTyped* cosStatement = handleUnaryMath(loc, "cos", EOpCos, arg0);
2115 TIntermTyped* sinAssign = intermediate.addAssign(EOpAssign, arg1, sinStatement, loc);
2116 TIntermTyped* cosAssign = intermediate.addAssign(EOpAssign, arg2, cosStatement, loc);
2117
2118 TIntermAggregate* compoundStatement = intermediate.makeAggregate(sinAssign, loc);
2119 compoundStatement = intermediate.growAggregate(compoundStatement, cosAssign);
2120 compoundStatement->setOperator(EOpSequence);
2121 compoundStatement->setLoc(loc);
LoopDawg4624a022016-06-20 13:26:59 -06002122 compoundStatement->setType(TType(EbtVoid));
LoopDawg592860c2016-06-09 08:57:35 -06002123
2124 node = compoundStatement;
2125
2126 break;
2127 }
2128
2129 case EOpClip:
2130 {
2131 // clip(a) -> if (any(a<0)) discard;
2132 TIntermTyped* arg0 = fnUnary->getOperand();
2133 TBasicType type0 = arg0->getBasicType();
2134 TIntermTyped* compareNode = nullptr;
2135
2136 // For non-scalars: per experiment with FXC compiler, discard if any component < 0.
2137 if (!arg0->isScalar()) {
2138 // component-wise compare: a < 0
2139 TIntermAggregate* less = new TIntermAggregate(EOpLessThan);
2140 less->getSequence().push_back(arg0);
2141 less->setLoc(loc);
2142
2143 // make vec or mat of bool matching dimensions of input
2144 less->setType(TType(EbtBool, EvqTemporary,
2145 arg0->getType().getVectorSize(),
2146 arg0->getType().getMatrixCols(),
2147 arg0->getType().getMatrixRows(),
2148 arg0->getType().isVector()));
2149
2150 // calculate # of components for comparison const
2151 const int constComponentCount =
2152 std::max(arg0->getType().getVectorSize(), 1) *
2153 std::max(arg0->getType().getMatrixCols(), 1) *
2154 std::max(arg0->getType().getMatrixRows(), 1);
2155
2156 TConstUnion zero;
2157 zero.setDConst(0.0);
2158 TConstUnionArray zeros(constComponentCount, zero);
2159
2160 less->getSequence().push_back(intermediate.addConstantUnion(zeros, arg0->getType(), loc, true));
2161
2162 compareNode = intermediate.addBuiltInFunctionCall(loc, EOpAny, true, less, TType(EbtBool));
2163 } else {
2164 TIntermTyped* zero = intermediate.addConstantUnion(0, type0, loc, true);
2165 compareNode = handleBinaryMath(loc, "clip", EOpLessThan, arg0, zero);
2166 }
2167
2168 TIntermBranch* killNode = intermediate.addBranch(EOpKill, loc);
2169
2170 node = new TIntermSelection(compareNode, killNode, nullptr);
2171 node->setLoc(loc);
2172
2173 break;
2174 }
2175
2176 case EOpLog10:
2177 {
2178 // log10(a) -> log2(a) * 0.301029995663981 (== 1/log2(10))
2179 TIntermTyped* arg0 = fnUnary->getOperand();
2180 TIntermTyped* log2 = handleUnaryMath(loc, "log2", EOpLog2, arg0);
2181 TIntermTyped* base = intermediate.addConstantUnion(0.301029995663981f, EbtFloat, loc, true);
2182
2183 node = handleBinaryMath(loc, "mul", EOpMul, log2, base);
2184
2185 break;
2186 }
2187
2188 case EOpDst:
2189 {
2190 // dest.x = 1;
2191 // dest.y = src0.y * src1.y;
2192 // dest.z = src0.z;
2193 // dest.w = src1.w;
2194
2195 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
2196 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
LoopDawg592860c2016-06-09 08:57:35 -06002197
LoopDawg592860c2016-06-09 08:57:35 -06002198 TIntermTyped* y = intermediate.addConstantUnion(1, loc, true);
2199 TIntermTyped* z = intermediate.addConstantUnion(2, loc, true);
2200 TIntermTyped* w = intermediate.addConstantUnion(3, loc, true);
2201
2202 TIntermTyped* src0y = intermediate.addIndex(EOpIndexDirect, arg0, y, loc);
2203 TIntermTyped* src1y = intermediate.addIndex(EOpIndexDirect, arg1, y, loc);
2204 TIntermTyped* src0z = intermediate.addIndex(EOpIndexDirect, arg0, z, loc);
2205 TIntermTyped* src1w = intermediate.addIndex(EOpIndexDirect, arg1, w, loc);
2206
2207 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
2208
2209 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
2210 dst->getSequence().push_back(handleBinaryMath(loc, "mul", EOpMul, src0y, src1y));
2211 dst->getSequence().push_back(src0z);
2212 dst->getSequence().push_back(src1w);
LoopDawg6e72fdd2016-06-15 09:50:24 -06002213 dst->setType(TType(EbtFloat, EvqTemporary, 4));
LoopDawg592860c2016-06-09 08:57:35 -06002214 dst->setLoc(loc);
2215 node = dst;
2216
2217 break;
2218 }
2219
LoopDawg58910702016-06-13 09:22:28 -06002220 case EOpInterlockedAdd: // optional last argument (if present) is assigned from return value
2221 case EOpInterlockedMin: // ...
2222 case EOpInterlockedMax: // ...
2223 case EOpInterlockedAnd: // ...
2224 case EOpInterlockedOr: // ...
2225 case EOpInterlockedXor: // ...
2226 case EOpInterlockedExchange: // always has output arg
2227 {
2228 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
2229 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
2230
2231 const bool isImage = arg0->getType().isImage();
2232 const TOperator atomicOp = mapAtomicOp(loc, op, isImage);
2233
2234 if (argAggregate->getSequence().size() > 2) {
2235 // optional output param is present. return value goes to arg2.
2236 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped();
2237
2238 TIntermAggregate* atomic = new TIntermAggregate(atomicOp);
2239 atomic->getSequence().push_back(arg0);
2240 atomic->getSequence().push_back(arg1);
2241 atomic->setLoc(loc);
2242 atomic->setType(arg0->getType());
2243 atomic->getWritableType().getQualifier().makeTemporary();
2244
2245 node = intermediate.addAssign(EOpAssign, arg2, atomic, loc);
2246 } else {
2247 // Set the matching operator. Since output is absent, this is all we need to do.
2248 node->getAsAggregate()->setOperator(atomicOp);
2249 }
2250
2251 break;
2252 }
2253
2254 case EOpInterlockedCompareExchange:
2255 {
2256 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // dest
2257 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // cmp
2258 TIntermTyped* arg2 = argAggregate->getSequence()[2]->getAsTyped(); // value
2259 TIntermTyped* arg3 = argAggregate->getSequence()[3]->getAsTyped(); // orig
2260
2261 const bool isImage = arg0->getType().isImage();
2262 TIntermAggregate* atomic = new TIntermAggregate(mapAtomicOp(loc, op, isImage));
2263 atomic->getSequence().push_back(arg0);
2264 atomic->getSequence().push_back(arg1);
2265 atomic->getSequence().push_back(arg2);
2266 atomic->setLoc(loc);
2267 atomic->setType(arg2->getType());
2268 atomic->getWritableType().getQualifier().makeTemporary();
2269
2270 node = intermediate.addAssign(EOpAssign, arg3, atomic, loc);
2271
2272 break;
2273 }
2274
LoopDawg6e72fdd2016-06-15 09:50:24 -06002275 case EOpEvaluateAttributeSnapped:
2276 {
2277 // SPIR-V InterpolateAtOffset uses float vec2 offset in pixels
2278 // HLSL uses int2 offset on a 16x16 grid in [-8..7] on x & y:
2279 // iU = (iU<<28)>>28
2280 // fU = ((float)iU)/16
2281 // Targets might handle this natively, in which case they can disable
2282 // decompositions.
2283
2284 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped(); // value
2285 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped(); // offset
2286
2287 TIntermTyped* i28 = intermediate.addConstantUnion(28, loc, true);
2288 TIntermTyped* iU = handleBinaryMath(loc, ">>", EOpRightShift,
2289 handleBinaryMath(loc, "<<", EOpLeftShift, arg1, i28),
2290 i28);
2291
2292 TIntermTyped* recip16 = intermediate.addConstantUnion((1.0/16.0), EbtFloat, loc, true);
2293 TIntermTyped* floatOffset = handleBinaryMath(loc, "mul", EOpMul,
2294 intermediate.addConversion(EOpConstructFloat,
2295 TType(EbtFloat, EvqTemporary, 2), iU),
2296 recip16);
2297
2298 TIntermAggregate* interp = new TIntermAggregate(EOpInterpolateAtOffset);
2299 interp->getSequence().push_back(arg0);
2300 interp->getSequence().push_back(floatOffset);
2301 interp->setLoc(loc);
2302 interp->setType(arg0->getType());
2303 interp->getWritableType().getQualifier().makeTemporary();
2304
2305 node = interp;
2306
2307 break;
2308 }
2309
2310 case EOpLit:
2311 {
2312 TIntermTyped* n_dot_l = argAggregate->getSequence()[0]->getAsTyped();
2313 TIntermTyped* n_dot_h = argAggregate->getSequence()[1]->getAsTyped();
2314 TIntermTyped* m = argAggregate->getSequence()[2]->getAsTyped();
2315
2316 TIntermAggregate* dst = new TIntermAggregate(EOpConstructVec4);
2317
2318 // Ambient
2319 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
2320
2321 // Diffuse:
2322 TIntermTyped* zero = intermediate.addConstantUnion(0.0, EbtFloat, loc, true);
2323 TIntermAggregate* diffuse = new TIntermAggregate(EOpMax);
2324 diffuse->getSequence().push_back(n_dot_l);
2325 diffuse->getSequence().push_back(zero);
2326 diffuse->setLoc(loc);
2327 diffuse->setType(TType(EbtFloat));
2328 dst->getSequence().push_back(diffuse);
2329
2330 // Specular:
2331 TIntermAggregate* min_ndot = new TIntermAggregate(EOpMin);
2332 min_ndot->getSequence().push_back(n_dot_l);
2333 min_ndot->getSequence().push_back(n_dot_h);
2334 min_ndot->setLoc(loc);
2335 min_ndot->setType(TType(EbtFloat));
2336
2337 TIntermTyped* compare = handleBinaryMath(loc, "<", EOpLessThan, min_ndot, zero);
2338 TIntermTyped* n_dot_h_m = handleBinaryMath(loc, "mul", EOpMul, n_dot_h, m); // n_dot_h * m
2339
2340 dst->getSequence().push_back(intermediate.addSelection(compare, zero, n_dot_h_m, loc));
2341
2342 // One:
2343 dst->getSequence().push_back(intermediate.addConstantUnion(1.0, EbtFloat, loc, true));
2344
2345 dst->setLoc(loc);
2346 dst->setType(TType(EbtFloat, EvqTemporary, 4));
2347 node = dst;
2348 break;
2349 }
2350
LoopDawg1b7fd0f2016-06-22 15:20:14 -06002351 case EOpAsDouble:
2352 {
2353 // asdouble accepts two 32 bit ints. we can use EOpUint64BitsToDouble, but must
2354 // first construct a uint64.
2355 TIntermTyped* arg0 = argAggregate->getSequence()[0]->getAsTyped();
2356 TIntermTyped* arg1 = argAggregate->getSequence()[1]->getAsTyped();
2357
2358 if (arg0->getType().isVector()) { // TODO: ...
2359 error(loc, "double2 conversion not implemented", "asdouble", "");
2360 break;
2361 }
2362
2363 TIntermAggregate* uint64 = new TIntermAggregate(EOpConstructUVec2);
2364
2365 uint64->getSequence().push_back(arg0);
2366 uint64->getSequence().push_back(arg1);
2367 uint64->setType(TType(EbtUint, EvqTemporary, 2)); // convert 2 uints to a uint2
2368 uint64->setLoc(loc);
2369
2370 // bitcast uint2 to a double
2371 TIntermTyped* convert = new TIntermUnary(EOpUint64BitsToDouble);
2372 convert->getAsUnaryNode()->setOperand(uint64);
2373 convert->setLoc(loc);
2374 convert->setType(TType(EbtDouble, EvqTemporary));
2375 node = convert;
2376
2377 break;
2378 }
2379
LoopDawg6e72fdd2016-06-15 09:50:24 -06002380 case EOpF16tof32:
2381 case EOpF32tof16:
2382 {
2383 // Temporary until decomposition is available.
2384 error(loc, "unimplemented intrinsic: handle natively", "f32tof16", "");
2385 break;
2386 }
2387
LoopDawg592860c2016-06-09 08:57:35 -06002388 default:
2389 break; // most pass through unchanged
2390 }
2391}
2392
John Kesseniche01a9bc2016-03-12 20:11:22 -07002393//
2394// Handle seeing function call syntax in the grammar, which could be any of
2395// - .length() method
2396// - constructor
2397// - a call to a built-in function mapped to an operator
2398// - a call to a built-in function that will remain a function call (e.g., texturing)
2399// - user function
2400// - subroutine call (not implemented yet)
2401//
2402TIntermTyped* HlslParseContext::handleFunctionCall(const TSourceLoc& loc, TFunction* function, TIntermNode* arguments)
2403{
2404 TIntermTyped* result = nullptr;
2405
2406 TOperator op = function->getBuiltInOp();
2407 if (op == EOpArrayLength)
2408 result = handleLengthMethod(loc, function, arguments);
2409 else if (op != EOpNull) {
2410 //
2411 // Then this should be a constructor.
2412 // Don't go through the symbol table for constructors.
2413 // Their parameters will be verified algorithmically.
2414 //
2415 TType type(EbtVoid); // use this to get the type back
2416 if (! constructorError(loc, arguments, *function, op, type)) {
2417 //
2418 // It's a constructor, of type 'type'.
2419 //
John Kessenicha26a5172016-07-28 15:29:35 -06002420 result = addConstructor(loc, arguments, type);
John Kesseniche01a9bc2016-03-12 20:11:22 -07002421 if (result == nullptr)
2422 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
2423 }
2424 } else {
2425 //
2426 // Find it in the symbol table.
2427 //
2428 const TFunction* fnCandidate;
2429 bool builtIn;
2430 fnCandidate = findFunction(loc, *function, builtIn);
2431 if (fnCandidate) {
2432 // This is a declared function that might map to
2433 // - a built-in operator,
2434 // - a built-in function not mapped to an operator, or
2435 // - a user function.
2436
2437 // Error check for a function requiring specific extensions present.
2438 if (builtIn && fnCandidate->getNumExtensions())
2439 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
2440
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002441 // Convert 'in' arguments
2442 if (arguments)
2443 addInputArgumentConversions(*fnCandidate, arguments);
John Kesseniche01a9bc2016-03-12 20:11:22 -07002444
2445 op = fnCandidate->getBuiltInOp();
2446 if (builtIn && op != EOpNull) {
2447 // A function call mapped to a built-in operation.
2448 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
2449 if (result == nullptr) {
2450 error(arguments->getLoc(), " wrong operand type", "Internal Error",
2451 "built in unary operator function. Type: %s",
2452 static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
2453 } else if (result->getAsOperator()) {
2454 builtInOpCheck(loc, *fnCandidate, *result->getAsOperator());
2455 }
2456 } else {
2457 // This is a function call not mapped to built-in operator.
2458 // It could still be a built-in function, but only if PureOperatorBuiltins == false.
2459 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
2460 TIntermAggregate* call = result->getAsAggregate();
2461 call->setName(fnCandidate->getMangledName());
2462
2463 // this is how we know whether the given function is a built-in function or a user-defined function
2464 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
2465 // if builtIn == true, it's definitely a built-in function with EOpNull
2466 if (! builtIn) {
2467 call->setUserDefined();
2468 intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
2469 }
2470 }
2471
2472 // Convert 'out' arguments. If it was a constant folded built-in, it won't be an aggregate anymore.
2473 // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
2474 // Also, build the qualifier list for user function calls, which are always called with an aggregate.
2475 if (result->getAsAggregate()) {
2476 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
2477 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
2478 TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
2479 qualifierList.push_back(qual);
2480 }
2481 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
2482 }
LoopDawg592860c2016-06-09 08:57:35 -06002483
LoopDawg4886f692016-06-29 10:58:58 -06002484 decomposeIntrinsic(loc, result, arguments); // HLSL->AST intrinsic decompositions
2485 decomposeSampleMethods(loc, result, arguments); // HLSL->AST sample method decompositions
John Kesseniche01a9bc2016-03-12 20:11:22 -07002486 }
2487 }
2488
2489 // generic error recovery
2490 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
2491 if (result == nullptr)
2492 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
2493
2494 return result;
2495}
2496
2497// Finish processing object.length(). This started earlier in handleDotDereference(), where
2498// the ".length" part was recognized and semantically checked, and finished here where the
2499// function syntax "()" is recognized.
2500//
2501// Return resulting tree node.
2502TIntermTyped* HlslParseContext::handleLengthMethod(const TSourceLoc& loc, TFunction* function, TIntermNode* intermNode)
2503{
2504 int length = 0;
2505
2506 if (function->getParamCount() > 0)
2507 error(loc, "method does not accept any arguments", function->getName().c_str(), "");
2508 else {
2509 const TType& type = intermNode->getAsTyped()->getType();
2510 if (type.isArray()) {
2511 if (type.isRuntimeSizedArray()) {
2512 // Create a unary op and let the back end handle it
2513 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
John Kesseniche01a9bc2016-03-12 20:11:22 -07002514 } else
2515 length = type.getOuterArraySize();
2516 } else if (type.isMatrix())
2517 length = type.getMatrixCols();
2518 else if (type.isVector())
2519 length = type.getVectorSize();
2520 else {
2521 // we should not get here, because earlier semantic checking should have prevented this path
2522 error(loc, ".length()", "unexpected use of .length()", "");
2523 }
2524 }
2525
2526 if (length == 0)
2527 length = 1;
2528
2529 return intermediate.addConstantUnion(length, loc);
2530}
2531
2532//
2533// Add any needed implicit conversions for function-call arguments to input parameters.
2534//
2535void HlslParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
2536{
2537 TIntermAggregate* aggregate = arguments->getAsAggregate();
John Kessenich5159d4f2016-09-19 00:06:19 -06002538 const auto setArg = [&](int argNum, TIntermNode* arg) {
2539 if (function.getParamCount() == 1)
2540 arguments = arg;
2541 else {
2542 if (aggregate)
2543 aggregate->getSequence()[argNum] = arg;
2544 else
2545 arguments = arg;
2546 }
2547 };
John Kesseniche01a9bc2016-03-12 20:11:22 -07002548
2549 // Process each argument's conversion
2550 for (int i = 0; i < function.getParamCount(); ++i) {
John Kessenichc86d38b2016-10-01 13:30:37 -06002551 if (! function[i].type->getQualifier().isParamInput())
2552 continue;
2553
John Kesseniche01a9bc2016-03-12 20:11:22 -07002554 // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
2555 // is the single argument itself or its children are the arguments. Only one argument
2556 // means take 'arguments' itself as the one argument.
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002557 TIntermTyped* arg = function.getParamCount() == 1
2558 ? arguments->getAsTyped()
2559 : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
John Kesseniche01a9bc2016-03-12 20:11:22 -07002560 if (*function[i].type != arg->getType()) {
John Kessenichc86d38b2016-10-01 13:30:37 -06002561 // In-qualified arguments just need an extra node added above the argument to
2562 // convert to the correct type.
2563 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
2564 arg = intermediate.addShapeConversion(EOpFunctionCall, *function[i].type, arg);
2565 setArg(i, arg);
John Kessenich5159d4f2016-09-19 00:06:19 -06002566 } else {
2567 if (shouldFlatten(arg->getType())) {
John Kessenich6714bcc2016-09-21 17:50:12 -06002568 // Will make a two-level subtree.
2569 // The deepest will copy member-by-member to build the structure to pass.
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002570 // The level above that will be a two-operand EOpComma sequence that follows the copy by the
John Kessenich6714bcc2016-09-21 17:50:12 -06002571 // object itself.
John Kessenich5159d4f2016-09-19 00:06:19 -06002572 TVariable* internalAggregate = makeInternalVariable("aggShadow", *function[i].type);
John Kessenich28b28142016-09-19 00:19:49 -06002573 internalAggregate->getWritableType().getQualifier().makeTemporary();
John Kessenich5159d4f2016-09-19 00:06:19 -06002574 TIntermSymbol* internalSymbolNode = new TIntermSymbol(internalAggregate->getUniqueId(),
2575 internalAggregate->getName(),
2576 internalAggregate->getType());
John Kessenicha08c9292016-10-01 17:17:55 -06002577 internalSymbolNode->setLoc(arg->getLoc());
John Kessenich6714bcc2016-09-21 17:50:12 -06002578 // This makes the deepest level, the member-wise copy
John Kessenicha08c9292016-10-01 17:17:55 -06002579 TIntermAggregate* assignAgg = handleAssign(arg->getLoc(), EOpAssign, internalSymbolNode, arg)->getAsAggregate();
John Kessenich6714bcc2016-09-21 17:50:12 -06002580
2581 // Now, pair that with the resulting aggregate.
John Kessenicha08c9292016-10-01 17:17:55 -06002582 assignAgg = intermediate.growAggregate(assignAgg, internalSymbolNode, arg->getLoc());
John Kessenich5159d4f2016-09-19 00:06:19 -06002583 assignAgg->setOperator(EOpComma);
John Kessenich6714bcc2016-09-21 17:50:12 -06002584 assignAgg->setType(internalAggregate->getType());
John Kessenich5159d4f2016-09-19 00:06:19 -06002585 setArg(i, assignAgg);
John Kesseniche01a9bc2016-03-12 20:11:22 -07002586 }
2587 }
2588 }
2589}
2590
2591//
2592// Add any needed implicit output conversions for function-call arguments. This
2593// can require a new tree topology, complicated further by whether the function
2594// has a return value.
2595//
2596// Returns a node of a subtree that evaluates to the return value of the function.
2597//
steve-lunarg90707962016-10-07 19:35:40 -06002598TIntermTyped* HlslParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode)
John Kesseniche01a9bc2016-03-12 20:11:22 -07002599{
2600 TIntermSequence& arguments = intermNode.getSequence();
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002601 const auto needsConversion = [&](int argNum) {
2602 return function[argNum].type->getQualifier().isParamOutput() &&
2603 (*function[argNum].type != arguments[argNum]->getAsTyped()->getType() ||
steve-lunarg90707962016-10-07 19:35:40 -06002604 shouldConvertLValue(arguments[argNum]) ||
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002605 shouldFlatten(arguments[argNum]->getAsTyped()->getType()));
2606 };
John Kesseniche01a9bc2016-03-12 20:11:22 -07002607
2608 // Will there be any output conversions?
2609 bool outputConversions = false;
2610 for (int i = 0; i < function.getParamCount(); ++i) {
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002611 if (needsConversion(i)) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07002612 outputConversions = true;
2613 break;
2614 }
2615 }
2616
2617 if (! outputConversions)
2618 return &intermNode;
2619
2620 // Setup for the new tree, if needed:
2621 //
2622 // Output conversions need a different tree topology.
2623 // Out-qualified arguments need a temporary of the correct type, with the call
2624 // followed by an assignment of the temporary to the original argument:
2625 // void: function(arg, ...) -> ( function(tempArg, ...), arg = tempArg, ...)
2626 // ret = function(arg, ...) -> ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
2627 // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
2628 TIntermTyped* conversionTree = nullptr;
2629 TVariable* tempRet = nullptr;
2630 if (intermNode.getBasicType() != EbtVoid) {
2631 // do the "tempRet = function(...), " bit from above
2632 tempRet = makeInternalVariable("tempReturn", intermNode.getType());
2633 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
2634 conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
2635 } else
2636 conversionTree = &intermNode;
2637
2638 conversionTree = intermediate.makeAggregate(conversionTree);
2639
2640 // Process each argument's conversion
2641 for (int i = 0; i < function.getParamCount(); ++i) {
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002642 if (needsConversion(i)) {
2643 // Out-qualified arguments needing conversion need to use the topology setup above.
2644 // Do the " ...(tempArg, ...), arg = tempArg" bit from above.
2645
2646 // Make a temporary for what the function expects the argument to look like.
2647 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
2648 tempArg->getWritableType().getQualifier().makeTemporary();
2649 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
2650
2651 // This makes the deepest level, the member-wise copy
steve-lunarg90707962016-10-07 19:35:40 -06002652 TIntermTyped* tempAssign = handleAssign(arguments[i]->getLoc(), EOpAssign, arguments[i]->getAsTyped(), tempArgNode);
2653 tempAssign = handleLvalue(arguments[i]->getLoc(), "assign", tempAssign);
John Kessenichd8fe2ca2016-10-01 17:11:21 -06002654 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
2655
2656 // replace the argument with another node for the same tempArg variable
2657 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
John Kesseniche01a9bc2016-03-12 20:11:22 -07002658 }
2659 }
2660
2661 // Finalize the tree topology (see bigger comment above).
2662 if (tempRet) {
2663 // do the "..., tempRet" bit from above
2664 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
2665 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
2666 }
2667 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
2668
2669 return conversionTree;
2670}
2671
2672//
2673// Do additional checking of built-in function calls that is not caught
2674// by normal semantic checks on argument type, extension tagging, etc.
2675//
2676// Assumes there has been a semantically correct match to a built-in function prototype.
2677//
2678void HlslParseContext::builtInOpCheck(const TSourceLoc& loc, const TFunction& fnCandidate, TIntermOperator& callNode)
2679{
2680 // Set up convenience accessors to the argument(s). There is almost always
2681 // multiple arguments for the cases below, but when there might be one,
2682 // check the unaryArg first.
2683 const TIntermSequence* argp = nullptr; // confusing to use [] syntax on a pointer, so this is to help get a reference
2684 const TIntermTyped* unaryArg = nullptr;
2685 const TIntermTyped* arg0 = nullptr;
2686 if (callNode.getAsAggregate()) {
2687 argp = &callNode.getAsAggregate()->getSequence();
2688 if (argp->size() > 0)
2689 arg0 = (*argp)[0]->getAsTyped();
2690 } else {
2691 assert(callNode.getAsUnaryNode());
2692 unaryArg = callNode.getAsUnaryNode()->getOperand();
2693 arg0 = unaryArg;
2694 }
2695 const TIntermSequence& aggArgs = *argp; // only valid when unaryArg is nullptr
2696
John Kesseniche01a9bc2016-03-12 20:11:22 -07002697 switch (callNode.getOp()) {
2698 case EOpTextureGather:
2699 case EOpTextureGatherOffset:
2700 case EOpTextureGatherOffsets:
2701 {
2702 // Figure out which variants are allowed by what extensions,
2703 // and what arguments must be constant for which situations.
2704
2705 TString featureString = fnCandidate.getName() + "(...)";
2706 const char* feature = featureString.c_str();
2707 int compArg = -1; // track which argument, if any, is the constant component argument
2708 switch (callNode.getOp()) {
2709 case EOpTextureGather:
2710 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
2711 // otherwise, need GL_ARB_texture_gather.
2712 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
2713 if (! fnCandidate[0].type->getSampler().shadow)
2714 compArg = 2;
2715 }
2716 break;
2717 case EOpTextureGatherOffset:
2718 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
2719 if (! fnCandidate[0].type->getSampler().shadow)
2720 compArg = 3;
2721 break;
2722 case EOpTextureGatherOffsets:
2723 if (! fnCandidate[0].type->getSampler().shadow)
2724 compArg = 3;
2725 break;
2726 default:
2727 break;
2728 }
2729
2730 if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
2731 if (aggArgs[compArg]->getAsConstantUnion()) {
2732 int value = aggArgs[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
2733 if (value < 0 || value > 3)
2734 error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
2735 } else
2736 error(loc, "must be a compile-time constant:", feature, "component argument");
2737 }
2738
2739 break;
2740 }
2741
2742 case EOpTextureOffset:
2743 case EOpTextureFetchOffset:
2744 case EOpTextureProjOffset:
2745 case EOpTextureLodOffset:
2746 case EOpTextureProjLodOffset:
2747 case EOpTextureGradOffset:
2748 case EOpTextureProjGradOffset:
2749 {
2750 // Handle texture-offset limits checking
2751 // Pick which argument has to hold constant offsets
2752 int arg = -1;
2753 switch (callNode.getOp()) {
2754 case EOpTextureOffset: arg = 2; break;
2755 case EOpTextureFetchOffset: arg = (arg0->getType().getSampler().dim != EsdRect) ? 3 : 2; break;
2756 case EOpTextureProjOffset: arg = 2; break;
2757 case EOpTextureLodOffset: arg = 3; break;
2758 case EOpTextureProjLodOffset: arg = 3; break;
2759 case EOpTextureGradOffset: arg = 4; break;
2760 case EOpTextureProjGradOffset: arg = 4; break;
2761 default:
2762 assert(0);
2763 break;
2764 }
2765
2766 if (arg > 0) {
2767 if (! aggArgs[arg]->getAsConstantUnion())
2768 error(loc, "argument must be compile-time constant", "texel offset", "");
2769 else {
2770 const TType& type = aggArgs[arg]->getAsTyped()->getType();
2771 for (int c = 0; c < type.getVectorSize(); ++c) {
2772 int offset = aggArgs[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
2773 if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
2774 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
2775 }
2776 }
2777 }
2778
2779 break;
2780 }
2781
2782 case EOpTextureQuerySamples:
2783 case EOpImageQuerySamples:
2784 break;
2785
2786 case EOpImageAtomicAdd:
2787 case EOpImageAtomicMin:
2788 case EOpImageAtomicMax:
2789 case EOpImageAtomicAnd:
2790 case EOpImageAtomicOr:
2791 case EOpImageAtomicXor:
2792 case EOpImageAtomicExchange:
2793 case EOpImageAtomicCompSwap:
2794 break;
2795
2796 case EOpInterpolateAtCentroid:
2797 case EOpInterpolateAtSample:
2798 case EOpInterpolateAtOffset:
John Kesseniche01a9bc2016-03-12 20:11:22 -07002799 // Make sure the first argument is an interpolant, or an array element of an interpolant
2800 if (arg0->getType().getQualifier().storage != EvqVaryingIn) {
2801 // It might still be an array element.
2802 //
2803 // We could check more, but the semantics of the first argument are already met; the
2804 // only way to turn an array into a float/vec* is array dereference and swizzle.
2805 //
2806 // ES and desktop 4.3 and earlier: swizzles may not be used
2807 // desktop 4.4 and later: swizzles may be used
2808 const TIntermTyped* base = TIntermediate::findLValueBase(arg0, true);
2809 if (base == nullptr || base->getType().getQualifier().storage != EvqVaryingIn)
2810 error(loc, "first argument must be an interpolant, or interpolant-array element", fnCandidate.getName().c_str(), "");
2811 }
2812 break;
2813
2814 default:
2815 break;
2816 }
2817}
2818
2819//
2820// Handle seeing a built-in constructor in a grammar production.
2821//
John Kessenichd016be12016-03-13 11:24:20 -06002822TFunction* HlslParseContext::handleConstructorCall(const TSourceLoc& loc, const TType& type)
John Kesseniche01a9bc2016-03-12 20:11:22 -07002823{
John Kessenicha26a5172016-07-28 15:29:35 -06002824 TOperator op = intermediate.mapTypeToConstructorOp(type);
John Kesseniche01a9bc2016-03-12 20:11:22 -07002825
2826 if (op == EOpNull) {
2827 error(loc, "cannot construct this type", type.getBasicString(), "");
John Kessenichd016be12016-03-13 11:24:20 -06002828 return nullptr;
John Kesseniche01a9bc2016-03-12 20:11:22 -07002829 }
2830
2831 TString empty("");
2832
2833 return new TFunction(&empty, type, op);
2834}
2835
2836//
John Kessenich630dd7d2016-06-12 23:52:12 -06002837// Handle seeing a "COLON semantic" at the end of a type declaration,
2838// by updating the type according to the semantic.
2839//
John Kessenich7735b942016-09-05 12:40:06 -06002840void HlslParseContext::handleSemantic(TSourceLoc loc, TQualifier& qualifier, const TString& semantic)
John Kessenich630dd7d2016-06-12 23:52:12 -06002841{
2842 // TODO: need to know if it's an input or an output
2843 // The following sketches what needs to be done, but can't be right
2844 // without taking into account stage and input/output.
Dan Baker26aa8a42016-08-25 17:13:25 -04002845
2846 TString semanticUpperCase = semantic;
2847 std::transform(semanticUpperCase.begin(), semanticUpperCase.end(), semanticUpperCase.begin(), ::toupper);
Dan Bakerdeec03c2016-08-25 11:59:17 -04002848 // in DX9, all outputs had to have a semantic associated with them, that was either consumed
2849 // by the system or was a specific register assignment
2850 // in DX10+, only semantics with the SV_ prefix have any meaning beyond decoration
2851 // Fxc will only accept DX9 style semantics in compat mode
2852 // Also, in DX10 if a SV value is present as the input of a stage, but isn't appropriate for that
2853 // stage, it would just be ignored as it is likely there as part of an output struct from one stage
2854 // to the next
John Kessenich630dd7d2016-06-12 23:52:12 -06002855
Dan Baker26aa8a42016-08-25 17:13:25 -04002856
2857 bool bParseDX9 = false;
John Kessenich81d47142016-08-29 16:07:29 -06002858 if (bParseDX9) {
Dan Baker26aa8a42016-08-25 17:13:25 -04002859 if (semanticUpperCase == "PSIZE")
John Kessenich7735b942016-09-05 12:40:06 -06002860 qualifier.builtIn = EbvPointSize;
Dan Bakerdeec03c2016-08-25 11:59:17 -04002861 else if (semantic == "FOG")
John Kessenich7735b942016-09-05 12:40:06 -06002862 qualifier.builtIn = EbvFogFragCoord;
Dan Baker26aa8a42016-08-25 17:13:25 -04002863 else if (semanticUpperCase == "DEPTH")
John Kessenich7735b942016-09-05 12:40:06 -06002864 qualifier.builtIn = EbvFragDepth;
Dan Baker26aa8a42016-08-25 17:13:25 -04002865 else if (semanticUpperCase == "VFACE")
John Kessenich7735b942016-09-05 12:40:06 -06002866 qualifier.builtIn = EbvFace;
Dan Baker26aa8a42016-08-25 17:13:25 -04002867 else if (semanticUpperCase == "VPOS")
John Kessenich7735b942016-09-05 12:40:06 -06002868 qualifier.builtIn = EbvFragCoord;
Dan Bakerdeec03c2016-08-25 11:59:17 -04002869 }
Dan Bakerdeec03c2016-08-25 11:59:17 -04002870
John Kessenich81d47142016-08-29 16:07:29 -06002871 //SV Position has a different meaning in vertex vs fragment
2872 if (semanticUpperCase == "SV_POSITION" && language != EShLangFragment)
John Kessenich7735b942016-09-05 12:40:06 -06002873 qualifier.builtIn = EbvPosition;
John Kessenich81d47142016-08-29 16:07:29 -06002874 else if (semanticUpperCase == "SV_POSITION" && language == EShLangFragment)
John Kessenich7735b942016-09-05 12:40:06 -06002875 qualifier.builtIn = EbvFragCoord;
John Kessenich81d47142016-08-29 16:07:29 -06002876 else if (semanticUpperCase == "SV_CLIPDISTANCE")
John Kessenich7735b942016-09-05 12:40:06 -06002877 qualifier.builtIn = EbvClipDistance;
John Kessenich81d47142016-08-29 16:07:29 -06002878 else if (semanticUpperCase == "SV_CULLDISTANCE")
John Kessenich7735b942016-09-05 12:40:06 -06002879 qualifier.builtIn = EbvCullDistance;
John Kessenich81d47142016-08-29 16:07:29 -06002880 else if (semanticUpperCase == "SV_VERTEXID")
John Kessenich7735b942016-09-05 12:40:06 -06002881 qualifier.builtIn = EbvVertexIndex;
John Kessenich81d47142016-08-29 16:07:29 -06002882 else if (semanticUpperCase == "SV_VIEWPORTARRAYINDEX")
John Kessenich7735b942016-09-05 12:40:06 -06002883 qualifier.builtIn = EbvViewportIndex;
John Kessenich81d47142016-08-29 16:07:29 -06002884 else if (semanticUpperCase == "SV_TESSFACTOR")
John Kessenich7735b942016-09-05 12:40:06 -06002885 qualifier.builtIn = EbvTessLevelOuter;
Dan Bakerdeec03c2016-08-25 11:59:17 -04002886
John Kessenich81d47142016-08-29 16:07:29 -06002887 //Targets are defined 0-7
2888 else if (semanticUpperCase == "SV_TARGET") {
John Kessenich7735b942016-09-05 12:40:06 -06002889 qualifier.builtIn = EbvNone;
2890 //qualifier.layoutLocation = 0;
John Kessenich81d47142016-08-29 16:07:29 -06002891 } else if (semanticUpperCase == "SV_TARGET0") {
John Kessenich7735b942016-09-05 12:40:06 -06002892 qualifier.builtIn = EbvNone;
2893 //qualifier.layoutLocation = 0;
John Kessenich81d47142016-08-29 16:07:29 -06002894 } else if (semanticUpperCase == "SV_TARGET1") {
John Kessenich7735b942016-09-05 12:40:06 -06002895 qualifier.builtIn = EbvNone;
2896 //qualifier.layoutLocation = 1;
John Kessenich81d47142016-08-29 16:07:29 -06002897 } else if (semanticUpperCase == "SV_TARGET2") {
John Kessenich7735b942016-09-05 12:40:06 -06002898 qualifier.builtIn = EbvNone;
2899 //qualifier.layoutLocation = 2;
John Kessenich81d47142016-08-29 16:07:29 -06002900 } else if (semanticUpperCase == "SV_TARGET3") {
John Kessenich7735b942016-09-05 12:40:06 -06002901 qualifier.builtIn = EbvNone;
2902 //qualifier.layoutLocation = 3;
John Kessenich81d47142016-08-29 16:07:29 -06002903 } else if (semanticUpperCase == "SV_TARGET4") {
John Kessenich7735b942016-09-05 12:40:06 -06002904 qualifier.builtIn = EbvNone;
2905 //qualifier.layoutLocation = 4;
John Kessenich81d47142016-08-29 16:07:29 -06002906 } else if (semanticUpperCase == "SV_TARGET5") {
John Kessenich7735b942016-09-05 12:40:06 -06002907 qualifier.builtIn = EbvNone;
2908 //qualifier.layoutLocation = 5;
John Kessenich81d47142016-08-29 16:07:29 -06002909 } else if (semanticUpperCase == "SV_TARGET6") {
John Kessenich7735b942016-09-05 12:40:06 -06002910 qualifier.builtIn = EbvNone;
2911 //qualifier.layoutLocation = 6;
John Kessenich81d47142016-08-29 16:07:29 -06002912 } else if (semanticUpperCase == "SV_TARGET7") {
John Kessenich7735b942016-09-05 12:40:06 -06002913 qualifier.builtIn = EbvNone;
2914 //qualifier.layoutLocation = 7;
John Kessenich81d47142016-08-29 16:07:29 -06002915 } else if (semanticUpperCase == "SV_SAMPLEINDEX")
John Kessenich7735b942016-09-05 12:40:06 -06002916 qualifier.builtIn = EbvSampleId;
John Kessenich81d47142016-08-29 16:07:29 -06002917 else if (semanticUpperCase == "SV_RENDERTARGETARRAYINDEX")
John Kessenich7735b942016-09-05 12:40:06 -06002918 qualifier.builtIn = EbvLayer;
John Kessenich81d47142016-08-29 16:07:29 -06002919 else if (semanticUpperCase == "SV_PRIMITIVEID")
John Kessenich7735b942016-09-05 12:40:06 -06002920 qualifier.builtIn = EbvPrimitiveId;
John Kessenich81d47142016-08-29 16:07:29 -06002921 else if (semanticUpperCase == "SV_OUTPUTCONTROLPOINTID")
John Kessenich7735b942016-09-05 12:40:06 -06002922 qualifier.builtIn = EbvInvocationId;
John Kessenich81d47142016-08-29 16:07:29 -06002923 else if (semanticUpperCase == "SV_ISFRONTFACE")
John Kessenich7735b942016-09-05 12:40:06 -06002924 qualifier.builtIn = EbvFace;
John Kessenich81d47142016-08-29 16:07:29 -06002925 else if (semanticUpperCase == "SV_INSTANCEID")
John Kessenich7735b942016-09-05 12:40:06 -06002926 qualifier.builtIn = EbvInstanceIndex;
John Kessenich81d47142016-08-29 16:07:29 -06002927 else if (semanticUpperCase == "SV_INSIDETESSFACTOR")
John Kessenich7735b942016-09-05 12:40:06 -06002928 qualifier.builtIn = EbvTessLevelInner;
John Kessenich81d47142016-08-29 16:07:29 -06002929 else if (semanticUpperCase == "SV_GSINSTANCEID")
John Kessenich7735b942016-09-05 12:40:06 -06002930 qualifier.builtIn = EbvInvocationId;
John Kessenich81d47142016-08-29 16:07:29 -06002931 else if (semanticUpperCase == "SV_GROUPTHREADID")
John Kessenich7735b942016-09-05 12:40:06 -06002932 qualifier.builtIn = EbvLocalInvocationId;
John Kessenich81d47142016-08-29 16:07:29 -06002933 else if (semanticUpperCase == "SV_GROUPID")
John Kessenich7735b942016-09-05 12:40:06 -06002934 qualifier.builtIn = EbvWorkGroupId;
John Kessenich81d47142016-08-29 16:07:29 -06002935 else if (semanticUpperCase == "SV_DOMAINLOCATION")
John Kessenich7735b942016-09-05 12:40:06 -06002936 qualifier.builtIn = EbvTessCoord;
John Kessenich81d47142016-08-29 16:07:29 -06002937 else if (semanticUpperCase == "SV_DEPTH")
John Kessenich7735b942016-09-05 12:40:06 -06002938 qualifier.builtIn = EbvFragDepth;
Dan Bakerdeec03c2016-08-25 11:59:17 -04002939
John Kessenich81d47142016-08-29 16:07:29 -06002940 //TODO, these need to get refined to be more specific
John Kessenich9e079532016-09-02 20:05:19 -06002941 else if( semanticUpperCase == "SV_DEPTHGREATEREQUAL")
John Kessenich7735b942016-09-05 12:40:06 -06002942 qualifier.builtIn = EbvFragDepthGreater;
John Kessenich9e079532016-09-02 20:05:19 -06002943 else if( semanticUpperCase == "SV_DEPTHLESSEQUAL")
John Kessenich7735b942016-09-05 12:40:06 -06002944 qualifier.builtIn = EbvFragDepthLesser;
John Kessenich9e079532016-09-02 20:05:19 -06002945 else if( semanticUpperCase == "SV_STENCILREF")
John Kessenich81d47142016-08-29 16:07:29 -06002946 error(loc, "unimplemented", "SV_STENCILREF", "");
2947 else if( semanticUpperCase == "SV_COVERAGE")
2948 error(loc, "unimplemented", "SV_COVERAGE", "");
John Kessenich630dd7d2016-06-12 23:52:12 -06002949}
2950
2951//
John Kessenich96e9f472016-07-29 14:28:39 -06002952// Handle seeing something like "PACKOFFSET LEFT_PAREN c[Subcomponent][.component] RIGHT_PAREN"
John Kessenich82d6baf2016-07-29 13:03:05 -06002953//
2954// 'location' has the "c[Subcomponent]" part.
2955// 'component' points to the "component" part, or nullptr if not present.
2956//
John Kessenich7735b942016-09-05 12:40:06 -06002957void HlslParseContext::handlePackOffset(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString& location,
2958 const glslang::TString* component)
John Kessenich82d6baf2016-07-29 13:03:05 -06002959{
2960 if (location.size() == 0 || location[0] != 'c') {
2961 error(loc, "expected 'c'", "packoffset", "");
2962 return;
2963 }
2964 if (location.size() == 1)
2965 return;
2966 if (! isdigit(location[1])) {
2967 error(loc, "expected number after 'c'", "packoffset", "");
2968 return;
2969 }
2970
John Kessenich7735b942016-09-05 12:40:06 -06002971 qualifier.layoutOffset = 16 * atoi(location.substr(1, location.size()).c_str());
John Kessenich96e9f472016-07-29 14:28:39 -06002972 if (component != nullptr) {
John Kessenich82d6baf2016-07-29 13:03:05 -06002973 int componentOffset = 0;
2974 switch ((*component)[0]) {
2975 case 'x': componentOffset = 0; break;
2976 case 'y': componentOffset = 4; break;
2977 case 'z': componentOffset = 8; break;
2978 case 'w': componentOffset = 12; break;
2979 default:
2980 componentOffset = -1;
2981 break;
2982 }
2983 if (componentOffset < 0 || component->size() > 1) {
2984 error(loc, "expected {x, y, z, w} for component", "packoffset", "");
2985 return;
2986 }
John Kessenich7735b942016-09-05 12:40:06 -06002987 qualifier.layoutOffset += componentOffset;
John Kessenich82d6baf2016-07-29 13:03:05 -06002988 }
2989}
2990
2991//
John Kessenich96e9f472016-07-29 14:28:39 -06002992// Handle seeing something like "REGISTER LEFT_PAREN [shader_profile,] Type# RIGHT_PAREN"
2993//
2994// 'profile' points to the shader_profile part, or nullptr if not present.
2995// 'desc' is the type# part.
2996//
John Kessenich7735b942016-09-05 12:40:06 -06002997void HlslParseContext::handleRegister(const TSourceLoc& loc, TQualifier& qualifier, const glslang::TString* profile,
John Kessenichcfd7ce82016-09-05 16:03:12 -06002998 const glslang::TString& desc, int subComponent, const glslang::TString* spaceDesc)
John Kessenich96e9f472016-07-29 14:28:39 -06002999{
3000 if (profile != nullptr)
3001 warn(loc, "ignoring shader_profile", "register", "");
3002
John Kessenichb38f0712016-07-30 10:29:54 -06003003 if (desc.size() < 1) {
3004 error(loc, "expected register type", "register", "");
John Kessenich96e9f472016-07-29 14:28:39 -06003005 return;
3006 }
3007
John Kessenichb38f0712016-07-30 10:29:54 -06003008 int regNumber = 0;
3009 if (desc.size() > 1) {
3010 if (isdigit(desc[1]))
3011 regNumber = atoi(desc.substr(1, desc.size()).c_str());
3012 else {
3013 error(loc, "expected register number after register type", "register", "");
3014 return;
3015 }
John Kessenich96e9f472016-07-29 14:28:39 -06003016 }
3017
John Kessenichb38f0712016-07-30 10:29:54 -06003018 // TODO: learn what all these really mean and how they interact with regNumber and subComponent
John Kessenich96e9f472016-07-29 14:28:39 -06003019 switch (desc[0]) {
3020 case 'b':
3021 case 't':
3022 case 'c':
3023 case 's':
John Kessenich7735b942016-09-05 12:40:06 -06003024 qualifier.layoutBinding = regNumber + subComponent;
John Kessenich96e9f472016-07-29 14:28:39 -06003025 break;
3026 default:
3027 warn(loc, "ignoring unrecognized register type", "register", "%c", desc[0]);
3028 break;
3029 }
John Kessenichcfd7ce82016-09-05 16:03:12 -06003030
3031 // space
3032 unsigned int setNumber;
3033 const auto crackSpace = [&]() {
3034 const int spaceLen = 5;
3035 if (spaceDesc->size() < spaceLen + 1)
3036 return false;
3037 if (spaceDesc->compare(0, spaceLen, "space") != 0)
3038 return false;
3039 if (! isdigit((*spaceDesc)[spaceLen]))
3040 return false;
3041 setNumber = atoi(spaceDesc->substr(spaceLen, spaceDesc->size()).c_str());
3042 return true;
3043 };
3044
3045 if (spaceDesc) {
3046 if (! crackSpace()) {
3047 error(loc, "expected spaceN", "register", "");
3048 return;
3049 }
3050 qualifier.layoutSet = setNumber;
3051 }
John Kessenich96e9f472016-07-29 14:28:39 -06003052}
3053
3054//
John Kesseniche01a9bc2016-03-12 20:11:22 -07003055// Same error message for all places assignments don't work.
3056//
3057void HlslParseContext::assignError(const TSourceLoc& loc, const char* op, TString left, TString right)
3058{
3059 error(loc, "", op, "cannot convert from '%s' to '%s'",
3060 right.c_str(), left.c_str());
3061}
3062
3063//
3064// Same error message for all places unary operations don't work.
3065//
3066void HlslParseContext::unaryOpError(const TSourceLoc& loc, const char* op, TString operand)
3067{
3068 error(loc, " wrong operand type", op,
3069 "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
3070 op, operand.c_str());
3071}
3072
3073//
3074// Same error message for all binary operations don't work.
3075//
3076void HlslParseContext::binaryOpError(const TSourceLoc& loc, const char* op, TString left, TString right)
3077{
3078 error(loc, " wrong operand types:", op,
3079 "no operation '%s' exists that takes a left-hand operand of type '%s' and "
3080 "a right operand of type '%s' (or there is no acceptable conversion)",
3081 op, left.c_str(), right.c_str());
3082}
3083
3084//
3085// A basic type of EbtVoid is a key that the name string was seen in the source, but
3086// it was not found as a variable in the symbol table. If so, give the error
3087// message and insert a dummy variable in the symbol table to prevent future errors.
3088//
3089void HlslParseContext::variableCheck(TIntermTyped*& nodePtr)
3090{
3091 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
3092 if (! symbol)
3093 return;
3094
3095 if (symbol->getType().getBasicType() == EbtVoid) {
3096 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
3097
3098 // Add to symbol table to prevent future error messages on the same name
3099 if (symbol->getName().size() > 0) {
3100 TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
3101 symbolTable.insert(*fakeVariable);
3102
3103 // substitute a symbol node for this new variable
3104 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
3105 }
3106 }
3107}
3108
3109//
3110// Both test, and if necessary spit out an error, to see if the node is really
3111// a constant.
3112//
3113void HlslParseContext::constantValueCheck(TIntermTyped* node, const char* token)
3114{
3115 if (node->getQualifier().storage != EvqConst)
3116 error(node->getLoc(), "constant expression required", token, "");
3117}
3118
3119//
3120// Both test, and if necessary spit out an error, to see if the node is really
3121// an integer.
3122//
3123void HlslParseContext::integerCheck(const TIntermTyped* node, const char* token)
3124{
3125 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
3126 return;
3127
3128 error(node->getLoc(), "scalar integer expression required", token, "");
3129}
3130
3131//
3132// Both test, and if necessary spit out an error, to see if we are currently
3133// globally scoped.
3134//
3135void HlslParseContext::globalCheck(const TSourceLoc& loc, const char* token)
3136{
3137 if (! symbolTable.atGlobalLevel())
3138 error(loc, "not allowed in nested scope", token, "");
3139}
3140
3141
John Kessenich7f349c72016-07-08 22:09:10 -06003142bool HlslParseContext::builtInName(const TString& /*identifier*/)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003143{
3144 return false;
3145}
3146
3147//
3148// Make sure there is enough data and not too many arguments provided to the
3149// constructor to build something of the type of the constructor. Also returns
3150// the type of the constructor.
3151//
3152// Returns true if there was an error in construction.
3153//
John Kessenich7f349c72016-07-08 22:09:10 -06003154bool HlslParseContext::constructorError(const TSourceLoc& loc, TIntermNode* /*node*/, TFunction& function,
3155 TOperator op, TType& type)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003156{
3157 type.shallowCopy(function.getType());
3158
3159 bool constructingMatrix = false;
3160 switch (op) {
3161 case EOpConstructTextureSampler:
3162 return constructorTextureSamplerError(loc, function);
3163 case EOpConstructMat2x2:
3164 case EOpConstructMat2x3:
3165 case EOpConstructMat2x4:
3166 case EOpConstructMat3x2:
3167 case EOpConstructMat3x3:
3168 case EOpConstructMat3x4:
3169 case EOpConstructMat4x2:
3170 case EOpConstructMat4x3:
3171 case EOpConstructMat4x4:
3172 case EOpConstructDMat2x2:
3173 case EOpConstructDMat2x3:
3174 case EOpConstructDMat2x4:
3175 case EOpConstructDMat3x2:
3176 case EOpConstructDMat3x3:
3177 case EOpConstructDMat3x4:
3178 case EOpConstructDMat4x2:
3179 case EOpConstructDMat4x3:
3180 case EOpConstructDMat4x4:
3181 constructingMatrix = true;
3182 break;
3183 default:
3184 break;
3185 }
3186
3187 //
3188 // Walk the arguments for first-pass checks and collection of information.
3189 //
3190
3191 int size = 0;
3192 bool constType = true;
3193 bool full = false;
3194 bool overFull = false;
3195 bool matrixInMatrix = false;
3196 bool arrayArg = false;
3197 for (int arg = 0; arg < function.getParamCount(); ++arg) {
3198 if (function[arg].type->isArray()) {
3199 if (! function[arg].type->isExplicitlySizedArray()) {
3200 // Can't construct from an unsized array.
3201 error(loc, "array argument must be sized", "constructor", "");
3202 return true;
3203 }
3204 arrayArg = true;
3205 }
3206 if (constructingMatrix && function[arg].type->isMatrix())
3207 matrixInMatrix = true;
3208
3209 // 'full' will go to true when enough args have been seen. If we loop
3210 // again, there is an extra argument.
3211 if (full) {
3212 // For vectors and matrices, it's okay to have too many components
3213 // available, but not okay to have unused arguments.
3214 overFull = true;
3215 }
3216
3217 size += function[arg].type->computeNumComponents();
3218 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
3219 full = true;
3220
3221 if (function[arg].type->getQualifier().storage != EvqConst)
3222 constType = false;
3223 }
3224
3225 if (constType)
3226 type.getQualifier().storage = EvqConst;
3227
3228 if (type.isArray()) {
3229 if (function.getParamCount() == 0) {
3230 error(loc, "array constructor must have at least one argument", "constructor", "");
3231 return true;
3232 }
3233
3234 if (type.isImplicitlySizedArray()) {
3235 // auto adapt the constructor type to the number of arguments
3236 type.changeOuterArraySize(function.getParamCount());
3237 } else if (type.getOuterArraySize() != function.getParamCount()) {
3238 error(loc, "array constructor needs one argument per array element", "constructor", "");
3239 return true;
3240 }
3241
3242 if (type.isArrayOfArrays()) {
3243 // Types have to match, but we're still making the type.
3244 // Finish making the type, and the comparison is done later
3245 // when checking for conversion.
3246 TArraySizes& arraySizes = type.getArraySizes();
3247
3248 // At least the dimensionalities have to match.
3249 if (! function[0].type->isArray() || arraySizes.getNumDims() != function[0].type->getArraySizes().getNumDims() + 1) {
3250 error(loc, "array constructor argument not correct type to construct array element", "constructior", "");
3251 return true;
3252 }
3253
3254 if (arraySizes.isInnerImplicit()) {
3255 // "Arrays of arrays ..., and the size for any dimension is optional"
3256 // That means we need to adopt (from the first argument) the other array sizes into the type.
3257 for (int d = 1; d < arraySizes.getNumDims(); ++d) {
3258 if (arraySizes.getDimSize(d) == UnsizedArraySize) {
3259 arraySizes.setDimSize(d, function[0].type->getArraySizes().getDimSize(d - 1));
3260 }
3261 }
3262 }
3263 }
3264 }
3265
3266 if (arrayArg && op != EOpConstructStruct && ! type.isArrayOfArrays()) {
3267 error(loc, "constructing non-array constituent from array argument", "constructor", "");
3268 return true;
3269 }
3270
3271 if (matrixInMatrix && ! type.isArray()) {
3272 return false;
3273 }
3274
3275 if (overFull) {
3276 error(loc, "too many arguments", "constructor", "");
3277 return true;
3278 }
3279
3280 if (op == EOpConstructStruct && ! type.isArray() && (int)type.getStruct()->size() != function.getParamCount()) {
3281 error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
3282 return true;
3283 }
3284
3285 if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
3286 (op == EOpConstructStruct && size < type.computeNumComponents())) {
3287 error(loc, "not enough data provided for construction", "constructor", "");
3288 return true;
3289 }
3290
John Kessenich7f349c72016-07-08 22:09:10 -06003291 // TIntermTyped* typed = node->getAsTyped();
John Kesseniche01a9bc2016-03-12 20:11:22 -07003292
3293 return false;
3294}
3295
3296// Verify all the correct semantics for constructing a combined texture/sampler.
3297// Return true if the semantics are incorrect.
3298bool HlslParseContext::constructorTextureSamplerError(const TSourceLoc& loc, const TFunction& function)
3299{
3300 TString constructorName = function.getType().getBasicTypeString(); // TODO: performance: should not be making copy; interface needs to change
3301 const char* token = constructorName.c_str();
3302
3303 // exactly two arguments needed
3304 if (function.getParamCount() != 2) {
3305 error(loc, "sampler-constructor requires two arguments", token, "");
3306 return true;
3307 }
3308
3309 // For now, not allowing arrayed constructors, the rest of this function
3310 // is set up to allow them, if this test is removed:
3311 if (function.getType().isArray()) {
3312 error(loc, "sampler-constructor cannot make an array of samplers", token, "");
3313 return true;
3314 }
3315
3316 // first argument
3317 // * the constructor's first argument must be a texture type
3318 // * the dimensionality (1D, 2D, 3D, Cube, Rect, Buffer, MS, and Array)
3319 // of the texture type must match that of the constructed sampler type
3320 // (that is, the suffixes of the type of the first argument and the
3321 // type of the constructor will be spelled the same way)
3322 if (function[0].type->getBasicType() != EbtSampler ||
3323 ! function[0].type->getSampler().isTexture() ||
3324 function[0].type->isArray()) {
3325 error(loc, "sampler-constructor first argument must be a scalar textureXXX type", token, "");
3326 return true;
3327 }
3328 // simulate the first argument's impact on the result type, so it can be compared with the encapsulated operator!=()
3329 TSampler texture = function.getType().getSampler();
3330 texture.combined = false;
3331 texture.shadow = false;
3332 if (texture != function[0].type->getSampler()) {
3333 error(loc, "sampler-constructor first argument must match type and dimensionality of constructor type", token, "");
3334 return true;
3335 }
3336
3337 // second argument
3338 // * the constructor's second argument must be a scalar of type
3339 // *sampler* or *samplerShadow*
3340 // * the presence or absence of depth comparison (Shadow) must match
3341 // between the constructed sampler type and the type of the second argument
3342 if (function[1].type->getBasicType() != EbtSampler ||
3343 ! function[1].type->getSampler().isPureSampler() ||
3344 function[1].type->isArray()) {
3345 error(loc, "sampler-constructor second argument must be a scalar type 'sampler'", token, "");
3346 return true;
3347 }
3348 if (function.getType().getSampler().shadow != function[1].type->getSampler().shadow) {
3349 error(loc, "sampler-constructor second argument presence of shadow must match constructor presence of shadow", token, "");
3350 return true;
3351 }
3352
3353 return false;
3354}
3355
3356// Checks to see if a void variable has been declared and raise an error message for such a case
3357//
3358// returns true in case of an error
3359//
3360bool HlslParseContext::voidErrorCheck(const TSourceLoc& loc, const TString& identifier, const TBasicType basicType)
3361{
3362 if (basicType == EbtVoid) {
3363 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
3364 return true;
3365 }
3366
3367 return false;
3368}
3369
3370// Checks to see if the node (for the expression) contains a scalar boolean expression or not
3371void HlslParseContext::boolCheck(const TSourceLoc& loc, const TIntermTyped* type)
3372{
3373 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
3374 error(loc, "boolean expression expected", "", "");
3375}
3376
John Kesseniche01a9bc2016-03-12 20:11:22 -07003377//
3378// Fix just a full qualifier (no variables or types yet, but qualifier is complete) at global level.
3379//
John Kessenich7f349c72016-07-08 22:09:10 -06003380void HlslParseContext::globalQualifierFix(const TSourceLoc&, TQualifier& qualifier)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003381{
3382 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
3383 switch (qualifier.storage) {
3384 case EvqIn:
3385 qualifier.storage = EvqVaryingIn;
3386 break;
3387 case EvqOut:
3388 qualifier.storage = EvqVaryingOut;
3389 break;
3390 default:
3391 break;
3392 }
3393}
3394
3395//
3396// Merge characteristics of the 'src' qualifier into the 'dst'.
3397// If there is duplication, issue error messages, unless 'force'
3398// is specified, which means to just override default settings.
3399//
3400// Also, when force is false, it will be assumed that 'src' follows
3401// 'dst', for the purpose of error checking order for versions
3402// that require specific orderings of qualifiers.
3403//
John Kessenich34e7ee72016-09-16 17:10:39 -06003404void HlslParseContext::mergeQualifiers(TQualifier& dst, const TQualifier& src)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003405{
3406 // Storage qualification
3407 if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
3408 dst.storage = src.storage;
3409 else if ((dst.storage == EvqIn && src.storage == EvqOut) ||
John Kessenich3d157c52016-07-25 16:05:33 -06003410 (dst.storage == EvqOut && src.storage == EvqIn))
John Kesseniche01a9bc2016-03-12 20:11:22 -07003411 dst.storage = EvqInOut;
3412 else if ((dst.storage == EvqIn && src.storage == EvqConst) ||
John Kessenich3d157c52016-07-25 16:05:33 -06003413 (dst.storage == EvqConst && src.storage == EvqIn))
John Kesseniche01a9bc2016-03-12 20:11:22 -07003414 dst.storage = EvqConstReadOnly;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003415
John Kesseniche01a9bc2016-03-12 20:11:22 -07003416 // Layout qualifiers
3417 mergeObjectLayoutQualifiers(dst, src, false);
3418
3419 // individual qualifiers
3420 bool repeated = false;
3421#define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
3422 MERGE_SINGLETON(invariant);
John Kessenich17f07862016-05-04 12:36:14 -06003423 MERGE_SINGLETON(noContraction);
John Kesseniche01a9bc2016-03-12 20:11:22 -07003424 MERGE_SINGLETON(centroid);
3425 MERGE_SINGLETON(smooth);
3426 MERGE_SINGLETON(flat);
3427 MERGE_SINGLETON(nopersp);
3428 MERGE_SINGLETON(patch);
3429 MERGE_SINGLETON(sample);
3430 MERGE_SINGLETON(coherent);
3431 MERGE_SINGLETON(volatil);
3432 MERGE_SINGLETON(restrict);
3433 MERGE_SINGLETON(readonly);
3434 MERGE_SINGLETON(writeonly);
3435 MERGE_SINGLETON(specConstant);
3436}
3437
3438// used to flatten the sampler type space into a single dimension
3439// correlates with the declaration of defaultSamplerPrecision[]
3440int HlslParseContext::computeSamplerTypeIndex(TSampler& sampler)
3441{
3442 int arrayIndex = sampler.arrayed ? 1 : 0;
3443 int shadowIndex = sampler.shadow ? 1 : 0;
3444 int externalIndex = sampler.external ? 1 : 0;
3445
3446 return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
3447}
3448
3449//
3450// Do size checking for an array type's size.
3451//
3452void HlslParseContext::arraySizeCheck(const TSourceLoc& loc, TIntermTyped* expr, TArraySize& sizePair)
3453{
3454 bool isConst = false;
3455 sizePair.size = 1;
3456 sizePair.node = nullptr;
3457
3458 TIntermConstantUnion* constant = expr->getAsConstantUnion();
3459 if (constant) {
3460 // handle true (non-specialization) constant
3461 sizePair.size = constant->getConstArray()[0].getIConst();
3462 isConst = true;
3463 } else {
3464 // see if it's a specialization constant instead
3465 if (expr->getQualifier().isSpecConstant()) {
3466 isConst = true;
3467 sizePair.node = expr;
3468 TIntermSymbol* symbol = expr->getAsSymbolNode();
3469 if (symbol && symbol->getConstArray().size() > 0)
3470 sizePair.size = symbol->getConstArray()[0].getIConst();
3471 }
3472 }
3473
3474 if (! isConst || (expr->getBasicType() != EbtInt && expr->getBasicType() != EbtUint)) {
3475 error(loc, "array size must be a constant integer expression", "", "");
3476 return;
3477 }
3478
3479 if (sizePair.size <= 0) {
3480 error(loc, "array size must be a positive integer", "", "");
3481 return;
3482 }
3483}
3484
3485//
3486// Require array to be completely sized
3487//
3488void HlslParseContext::arraySizeRequiredCheck(const TSourceLoc& loc, const TArraySizes& arraySizes)
3489{
3490 if (arraySizes.isImplicit())
3491 error(loc, "array size required", "", "");
3492}
3493
3494void HlslParseContext::structArrayCheck(const TSourceLoc& /*loc*/, const TType& type)
3495{
3496 const TTypeList& structure = *type.getStruct();
3497 for (int m = 0; m < (int)structure.size(); ++m) {
3498 const TType& member = *structure[m].type;
3499 if (member.isArray())
3500 arraySizeRequiredCheck(structure[m].loc, *member.getArraySizes());
3501 }
3502}
3503
3504// Merge array dimensions listed in 'sizes' onto the type's array dimensions.
3505//
3506// From the spec: "vec4[2] a[3]; // size-3 array of size-2 array of vec4"
3507//
3508// That means, the 'sizes' go in front of the 'type' as outermost sizes.
3509// 'type' is the type part of the declaration (to the left)
3510// 'sizes' is the arrayness tagged on the identifier (to the right)
3511//
3512void HlslParseContext::arrayDimMerge(TType& type, const TArraySizes* sizes)
3513{
3514 if (sizes)
3515 type.addArrayOuterSizes(*sizes);
3516}
3517
3518//
3519// Do all the semantic checking for declaring or redeclaring an array, with and
3520// without a size, and make the right changes to the symbol table.
3521//
3522void HlslParseContext::declareArray(const TSourceLoc& loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
3523{
3524 if (! symbol) {
3525 bool currentScope;
3526 symbol = symbolTable.find(identifier, nullptr, &currentScope);
3527
3528 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
3529 // bad shader (errors already reported) trying to redeclare a built-in name as an array
3530 return;
3531 }
3532 if (symbol == nullptr || ! currentScope) {
3533 //
3534 // Successfully process a new definition.
3535 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
3536 //
3537 symbol = new TVariable(&identifier, type);
3538 symbolTable.insert(*symbol);
3539 newDeclaration = true;
3540
John Kesseniche01a9bc2016-03-12 20:11:22 -07003541 return;
3542 }
3543 if (symbol->getAsAnonMember()) {
3544 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
3545 symbol = nullptr;
3546 return;
3547 }
3548 }
3549
3550 //
3551 // Process a redeclaration.
3552 //
3553
3554 if (! symbol) {
3555 error(loc, "array variable name expected", identifier.c_str(), "");
3556 return;
3557 }
3558
3559 // redeclareBuiltinVariable() should have already done the copyUp()
3560 TType& existingType = symbol->getWritableType();
3561
3562
3563 if (existingType.isExplicitlySizedArray()) {
3564 // be more lenient for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
John Kesseniche01a9bc2016-03-12 20:11:22 -07003565 return;
3566 }
3567
3568 existingType.updateArraySizes(type);
John Kesseniche01a9bc2016-03-12 20:11:22 -07003569}
3570
3571void HlslParseContext::updateImplicitArraySize(const TSourceLoc& loc, TIntermNode *node, int index)
3572{
3573 // maybe there is nothing to do...
3574 TIntermTyped* typedNode = node->getAsTyped();
3575 if (typedNode->getType().getImplicitArraySize() > index)
3576 return;
3577
3578 // something to do...
3579
3580 // Figure out what symbol to lookup, as we will use its type to edit for the size change,
3581 // as that type will be shared through shallow copies for future references.
3582 TSymbol* symbol = nullptr;
3583 int blockIndex = -1;
3584 const TString* lookupName = nullptr;
3585 if (node->getAsSymbolNode())
3586 lookupName = &node->getAsSymbolNode()->getName();
3587 else if (node->getAsBinaryNode()) {
3588 const TIntermBinary* deref = node->getAsBinaryNode();
3589 // This has to be the result of a block dereference, unless it's bad shader code
3590 // If it's a uniform block, then an error will be issued elsewhere, but
3591 // return early now to avoid crashing later in this function.
3592 if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
3593 deref->getLeft()->getType().getQualifier().storage == EvqUniform ||
3594 deref->getRight()->getAsConstantUnion() == nullptr)
3595 return;
3596
3597 blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
3598
3599 lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
3600 if (IsAnonymous(*lookupName))
3601 lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
3602 }
3603
3604 // Lookup the symbol, should only fail if shader code is incorrect
3605 symbol = symbolTable.find(*lookupName);
3606 if (symbol == nullptr)
3607 return;
3608
3609 if (symbol->getAsFunction()) {
3610 error(loc, "array variable name expected", symbol->getName().c_str(), "");
3611 return;
3612 }
3613
3614 symbol->getWritableType().setImplicitArraySize(index + 1);
3615}
3616
3617//
3618// See if the identifier is a built-in symbol that can be redeclared, and if so,
3619// copy the symbol table's read-only built-in variable to the current
3620// global level, where it can be modified based on the passed in type.
3621//
3622// Returns nullptr if no redeclaration took place; meaning a normal declaration still
3623// needs to occur for it, not necessarily an error.
3624//
3625// Returns a redeclared and type-modified variable if a redeclared occurred.
3626//
John Kessenich7f349c72016-07-08 22:09:10 -06003627TSymbol* HlslParseContext::redeclareBuiltinVariable(const TSourceLoc& /*loc*/, const TString& identifier,
3628 const TQualifier& /*qualifier*/,
3629 const TShaderQualifiers& /*publicType*/, bool& /*newDeclaration*/)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003630{
3631 if (! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
3632 return nullptr;
3633
3634 return nullptr;
3635}
3636
3637//
3638// Either redeclare the requested block, or give an error message why it can't be done.
3639//
3640// TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
3641void HlslParseContext::redeclareBuiltinBlock(const TSourceLoc& loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
3642{
3643 // Redeclaring a built-in block...
3644
3645 // Blocks with instance names are easy to find, lookup the instance name,
3646 // Anonymous blocks need to be found via a member.
3647 bool builtIn;
3648 TSymbol* block;
3649 if (instanceName)
3650 block = symbolTable.find(*instanceName, &builtIn);
3651 else
3652 block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
3653
3654 // If the block was not found, this must be a version/profile/stage
3655 // that doesn't have it, or the instance name is wrong.
3656 const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
3657 if (! block) {
3658 error(loc, "no declaration found for redeclaration", errorName, "");
3659 return;
3660 }
3661 // Built-in blocks cannot be redeclared more than once, which if happened,
3662 // we'd be finding the already redeclared one here, rather than the built in.
3663 if (! builtIn) {
3664 error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
3665 return;
3666 }
3667
3668 // Copy the block to make a writable version, to insert into the block table after editing.
3669 block = symbolTable.copyUpDeferredInsert(block);
3670
3671 if (block->getType().getBasicType() != EbtBlock) {
3672 error(loc, "cannot redeclare a non block as a block", errorName, "");
3673 return;
3674 }
3675
3676 // Edit and error check the container against the redeclaration
3677 // - remove unused members
3678 // - ensure remaining qualifiers/types match
3679 TType& type = block->getWritableType();
3680 TTypeList::iterator member = type.getWritableStruct()->begin();
3681 size_t numOriginalMembersFound = 0;
3682 while (member != type.getStruct()->end()) {
3683 // look for match
3684 bool found = false;
3685 TTypeList::const_iterator newMember;
3686 TSourceLoc memberLoc;
3687 memberLoc.init();
3688 for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
3689 if (member->type->getFieldName() == newMember->type->getFieldName()) {
3690 found = true;
3691 memberLoc = newMember->loc;
3692 break;
3693 }
3694 }
3695
3696 if (found) {
3697 ++numOriginalMembersFound;
3698 // - ensure match between redeclared members' types
3699 // - check for things that can't be changed
3700 // - update things that can be changed
3701 TType& oldType = *member->type;
3702 const TType& newType = *newMember->type;
3703 if (! newType.sameElementType(oldType))
3704 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
3705 if (oldType.isArray() != newType.isArray())
3706 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
3707 else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
3708 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
3709 if (newType.getQualifier().isMemory())
3710 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
3711 if (newType.getQualifier().hasLayout())
3712 error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
3713 if (newType.getQualifier().patch)
3714 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
3715 oldType.getQualifier().centroid = newType.getQualifier().centroid;
3716 oldType.getQualifier().sample = newType.getQualifier().sample;
3717 oldType.getQualifier().invariant = newType.getQualifier().invariant;
John Kessenich17f07862016-05-04 12:36:14 -06003718 oldType.getQualifier().noContraction = newType.getQualifier().noContraction;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003719 oldType.getQualifier().smooth = newType.getQualifier().smooth;
3720 oldType.getQualifier().flat = newType.getQualifier().flat;
3721 oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
3722
3723 // go to next member
3724 ++member;
3725 } else {
3726 // For missing members of anonymous blocks that have been redeclared,
3727 // hide the original (shared) declaration.
3728 // Instance-named blocks can just have the member removed.
3729 if (instanceName)
3730 member = type.getWritableStruct()->erase(member);
3731 else {
3732 member->type->hideMember();
3733 ++member;
3734 }
3735 }
3736 }
3737
3738 if (numOriginalMembersFound < newTypeList.size())
3739 error(loc, "block redeclaration has extra members", blockName.c_str(), "");
3740 if (type.isArray() != (arraySizes != nullptr))
3741 error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
3742 else if (type.isArray()) {
3743 if (type.isExplicitlySizedArray() && arraySizes->getOuterSize() == UnsizedArraySize)
3744 error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
3745 else if (type.isExplicitlySizedArray() && type.getArraySizes() != *arraySizes)
3746 error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
3747 else if (type.isImplicitlySizedArray() && arraySizes->getOuterSize() != UnsizedArraySize)
3748 type.changeOuterArraySize(arraySizes->getOuterSize());
3749 }
3750
3751 symbolTable.insert(*block);
3752
John Kesseniche01a9bc2016-03-12 20:11:22 -07003753 // Save it in the AST for linker use.
3754 intermediate.addSymbolLinkageNode(linkage, *block);
3755}
3756
John Kessenich5aa59e22016-06-17 15:50:47 -06003757void HlslParseContext::paramFix(TType& type)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003758{
John Kessenich5aa59e22016-06-17 15:50:47 -06003759 switch (type.getQualifier().storage) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07003760 case EvqConst:
John Kesseniche01a9bc2016-03-12 20:11:22 -07003761 type.getQualifier().storage = EvqConstReadOnly;
3762 break;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003763 case EvqGlobal:
3764 case EvqTemporary:
3765 type.getQualifier().storage = EvqIn;
3766 break;
3767 default:
John Kesseniche01a9bc2016-03-12 20:11:22 -07003768 break;
3769 }
3770}
3771
John Kesseniche01a9bc2016-03-12 20:11:22 -07003772void HlslParseContext::specializationCheck(const TSourceLoc& loc, const TType& type, const char* op)
3773{
3774 if (type.containsSpecializationSize())
3775 error(loc, "can't use with types containing arrays sized with a specialization constant", op, "");
3776}
3777
3778//
3779// Layout qualifier stuff.
3780//
3781
3782// Put the id's layout qualification into the public type, for qualifiers not having a number set.
3783// This is before we know any type information for error checking.
John Kessenichb9e39122016-08-17 10:22:08 -06003784void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003785{
3786 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
3787
3788 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
John Kessenich10f7fc72016-09-25 20:25:06 -06003789 qualifier.layoutMatrix = ElmRowMajor;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003790 return;
3791 }
3792 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
John Kessenich10f7fc72016-09-25 20:25:06 -06003793 qualifier.layoutMatrix = ElmColumnMajor;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003794 return;
3795 }
John Kesseniche01a9bc2016-03-12 20:11:22 -07003796 if (id == "push_constant") {
3797 requireVulkan(loc, "push_constant");
John Kessenichb9e39122016-08-17 10:22:08 -06003798 qualifier.layoutPushConstant = true;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003799 return;
3800 }
3801 if (language == EShLangGeometry || language == EShLangTessEvaluation) {
3802 if (id == TQualifier::getGeometryString(ElgTriangles)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003803 //publicType.shaderQualifiers.geometry = ElgTriangles;
3804 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003805 return;
3806 }
3807 if (language == EShLangGeometry) {
3808 if (id == TQualifier::getGeometryString(ElgPoints)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003809 //publicType.shaderQualifiers.geometry = ElgPoints;
3810 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003811 return;
3812 }
3813 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003814 //publicType.shaderQualifiers.geometry = ElgLineStrip;
3815 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003816 return;
3817 }
3818 if (id == TQualifier::getGeometryString(ElgLines)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003819 //publicType.shaderQualifiers.geometry = ElgLines;
3820 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003821 return;
3822 }
3823 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003824 //publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
3825 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003826 return;
3827 }
3828 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003829 //publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
3830 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003831 return;
3832 }
3833 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003834 //publicType.shaderQualifiers.geometry = ElgTriangleStrip;
3835 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003836 return;
3837 }
3838 } else {
3839 assert(language == EShLangTessEvaluation);
3840
3841 // input primitive
3842 if (id == TQualifier::getGeometryString(ElgTriangles)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003843 //publicType.shaderQualifiers.geometry = ElgTriangles;
3844 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003845 return;
3846 }
3847 if (id == TQualifier::getGeometryString(ElgQuads)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003848 //publicType.shaderQualifiers.geometry = ElgQuads;
3849 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003850 return;
3851 }
3852 if (id == TQualifier::getGeometryString(ElgIsolines)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003853 //publicType.shaderQualifiers.geometry = ElgIsolines;
3854 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003855 return;
3856 }
3857
3858 // vertex spacing
3859 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003860 //publicType.shaderQualifiers.spacing = EvsEqual;
3861 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003862 return;
3863 }
3864 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003865 //publicType.shaderQualifiers.spacing = EvsFractionalEven;
3866 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003867 return;
3868 }
3869 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003870 //publicType.shaderQualifiers.spacing = EvsFractionalOdd;
3871 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003872 return;
3873 }
3874
3875 // triangle order
3876 if (id == TQualifier::getVertexOrderString(EvoCw)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003877 //publicType.shaderQualifiers.order = EvoCw;
3878 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003879 return;
3880 }
3881 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003882 //publicType.shaderQualifiers.order = EvoCcw;
3883 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003884 return;
3885 }
3886
3887 // point mode
3888 if (id == "point_mode") {
John Kessenichb9e39122016-08-17 10:22:08 -06003889 //publicType.shaderQualifiers.pointMode = true;
3890 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003891 return;
3892 }
3893 }
3894 }
3895 if (language == EShLangFragment) {
3896 if (id == "origin_upper_left") {
John Kessenichb9e39122016-08-17 10:22:08 -06003897 //publicType.shaderQualifiers.originUpperLeft = true;
3898 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003899 return;
3900 }
3901 if (id == "pixel_center_integer") {
John Kessenichb9e39122016-08-17 10:22:08 -06003902 //publicType.shaderQualifiers.pixelCenterInteger = true;
3903 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003904 return;
3905 }
3906 if (id == "early_fragment_tests") {
John Kessenichb9e39122016-08-17 10:22:08 -06003907 //publicType.shaderQualifiers.earlyFragmentTests = true;
3908 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003909 return;
3910 }
3911 for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth + 1)) {
3912 if (id == TQualifier::getLayoutDepthString(depth)) {
John Kessenichb9e39122016-08-17 10:22:08 -06003913 //publicType.shaderQualifiers.layoutDepth = depth;
3914 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003915 return;
3916 }
3917 }
3918 if (id.compare(0, 13, "blend_support") == 0) {
3919 bool found = false;
3920 for (TBlendEquationShift be = (TBlendEquationShift)0; be < EBlendCount; be = (TBlendEquationShift)(be + 1)) {
3921 if (id == TQualifier::getBlendEquationString(be)) {
3922 requireExtensions(loc, 1, &E_GL_KHR_blend_equation_advanced, "blend equation");
3923 intermediate.addBlendEquation(be);
John Kessenichb9e39122016-08-17 10:22:08 -06003924 //publicType.shaderQualifiers.blendEquation = true;
3925 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07003926 found = true;
3927 break;
3928 }
3929 }
3930 if (! found)
3931 error(loc, "unknown blend equation", "blend_support", "");
3932 return;
3933 }
3934 }
3935 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
3936}
3937
3938// Put the id's layout qualifier value into the public type, for qualifiers having a number set.
3939// This is before we know any type information for error checking.
John Kessenichb9e39122016-08-17 10:22:08 -06003940void HlslParseContext::setLayoutQualifier(const TSourceLoc& loc, TQualifier& qualifier, TString& id, const TIntermTyped* node)
John Kesseniche01a9bc2016-03-12 20:11:22 -07003941{
3942 const char* feature = "layout-id value";
John Kessenich7f349c72016-07-08 22:09:10 -06003943 //const char* nonLiteralFeature = "non-literal layout-id value";
John Kesseniche01a9bc2016-03-12 20:11:22 -07003944
3945 integerCheck(node, feature);
3946 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
3947 int value = 0;
3948 if (constUnion) {
3949 value = constUnion->getConstArray()[0].getIConst();
3950 }
3951
3952 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
3953
3954 if (id == "offset") {
John Kessenichb9e39122016-08-17 10:22:08 -06003955 qualifier.layoutOffset = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003956 return;
3957 } else if (id == "align") {
3958 // "The specified alignment must be a power of 2, or a compile-time error results."
3959 if (! IsPow2(value))
3960 error(loc, "must be a power of 2", "align", "");
3961 else
John Kessenichb9e39122016-08-17 10:22:08 -06003962 qualifier.layoutAlign = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003963 return;
3964 } else if (id == "location") {
3965 if ((unsigned int)value >= TQualifier::layoutLocationEnd)
3966 error(loc, "location is too large", id.c_str(), "");
3967 else
John Kessenichb9e39122016-08-17 10:22:08 -06003968 qualifier.layoutLocation = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003969 return;
3970 } else if (id == "set") {
3971 if ((unsigned int)value >= TQualifier::layoutSetEnd)
3972 error(loc, "set is too large", id.c_str(), "");
3973 else
John Kessenichb9e39122016-08-17 10:22:08 -06003974 qualifier.layoutSet = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003975 return;
3976 } else if (id == "binding") {
3977 if ((unsigned int)value >= TQualifier::layoutBindingEnd)
3978 error(loc, "binding is too large", id.c_str(), "");
3979 else
John Kessenichb9e39122016-08-17 10:22:08 -06003980 qualifier.layoutBinding = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003981 return;
3982 } else if (id == "component") {
3983 if ((unsigned)value >= TQualifier::layoutComponentEnd)
3984 error(loc, "component is too large", id.c_str(), "");
3985 else
John Kessenichb9e39122016-08-17 10:22:08 -06003986 qualifier.layoutComponent = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07003987 return;
3988 } else if (id.compare(0, 4, "xfb_") == 0) {
3989 // "Any shader making any static use (after preprocessing) of any of these
3990 // *xfb_* qualifiers will cause the shader to be in a transform feedback
3991 // capturing mode and hence responsible for describing the transform feedback
3992 // setup."
3993 intermediate.setXfbMode();
3994 if (id == "xfb_buffer") {
3995 // "It is a compile-time error to specify an *xfb_buffer* that is greater than
3996 // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
3997 if (value >= resources.maxTransformFeedbackBuffers)
3998 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);
3999 if (value >= (int)TQualifier::layoutXfbBufferEnd)
4000 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd - 1);
4001 else
John Kessenichb9e39122016-08-17 10:22:08 -06004002 qualifier.layoutXfbBuffer = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004003 return;
4004 } else if (id == "xfb_offset") {
4005 if (value >= (int)TQualifier::layoutXfbOffsetEnd)
4006 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd - 1);
4007 else
John Kessenichb9e39122016-08-17 10:22:08 -06004008 qualifier.layoutXfbOffset = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004009 return;
4010 } else if (id == "xfb_stride") {
4011 // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the
4012 // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
4013 if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
4014 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
4015 else if (value >= (int)TQualifier::layoutXfbStrideEnd)
4016 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd - 1);
4017 if (value < (int)TQualifier::layoutXfbStrideEnd)
John Kessenichb9e39122016-08-17 10:22:08 -06004018 qualifier.layoutXfbStride = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004019 return;
4020 }
4021 }
4022
4023 if (id == "input_attachment_index") {
4024 requireVulkan(loc, "input_attachment_index");
4025 if (value >= (int)TQualifier::layoutAttachmentEnd)
4026 error(loc, "attachment index is too large", id.c_str(), "");
4027 else
John Kessenichb9e39122016-08-17 10:22:08 -06004028 qualifier.layoutAttachment = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004029 return;
4030 }
4031 if (id == "constant_id") {
4032 requireSpv(loc, "constant_id");
4033 if (value >= (int)TQualifier::layoutSpecConstantIdEnd) {
4034 error(loc, "specialization-constant id is too large", id.c_str(), "");
4035 } else {
John Kessenichb9e39122016-08-17 10:22:08 -06004036 qualifier.layoutSpecConstantId = value;
4037 qualifier.specConstant = true;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004038 if (! intermediate.addUsedConstantId(value))
4039 error(loc, "specialization-constant id already used", id.c_str(), "");
4040 }
4041 return;
4042 }
4043
4044 switch (language) {
4045 case EShLangVertex:
4046 break;
4047
4048 case EShLangTessControl:
4049 if (id == "vertices") {
4050 if (value == 0)
4051 error(loc, "must be greater than 0", "vertices", "");
4052 else
John Kessenichb9e39122016-08-17 10:22:08 -06004053 //publicType.shaderQualifiers.vertices = value;
4054 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004055 return;
4056 }
4057 break;
4058
4059 case EShLangTessEvaluation:
4060 break;
4061
4062 case EShLangGeometry:
4063 if (id == "invocations") {
4064 if (value == 0)
4065 error(loc, "must be at least 1", "invocations", "");
4066 else
John Kessenichb9e39122016-08-17 10:22:08 -06004067 //publicType.shaderQualifiers.invocations = value;
4068 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004069 return;
4070 }
4071 if (id == "max_vertices") {
John Kessenichb9e39122016-08-17 10:22:08 -06004072 //publicType.shaderQualifiers.vertices = value;
4073 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004074 if (value > resources.maxGeometryOutputVertices)
4075 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
4076 return;
4077 }
4078 if (id == "stream") {
John Kessenichb9e39122016-08-17 10:22:08 -06004079 qualifier.layoutStream = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004080 return;
4081 }
4082 break;
4083
4084 case EShLangFragment:
4085 if (id == "index") {
John Kessenichb9e39122016-08-17 10:22:08 -06004086 qualifier.layoutIndex = value;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004087 return;
4088 }
4089 break;
4090
4091 case EShLangCompute:
4092 if (id.compare(0, 11, "local_size_") == 0) {
4093 if (id == "local_size_x") {
John Kessenichb9e39122016-08-17 10:22:08 -06004094 //publicType.shaderQualifiers.localSize[0] = value;
4095 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004096 return;
4097 }
4098 if (id == "local_size_y") {
John Kessenichb9e39122016-08-17 10:22:08 -06004099 //publicType.shaderQualifiers.localSize[1] = value;
4100 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004101 return;
4102 }
4103 if (id == "local_size_z") {
John Kessenichb9e39122016-08-17 10:22:08 -06004104 //publicType.shaderQualifiers.localSize[2] = value;
4105 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004106 return;
4107 }
John Kessenichb901ade2016-06-16 20:59:42 -06004108 if (spvVersion.spv != 0) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07004109 if (id == "local_size_x_id") {
John Kessenichb9e39122016-08-17 10:22:08 -06004110 //publicType.shaderQualifiers.localSizeSpecId[0] = value;
4111 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004112 return;
4113 }
4114 if (id == "local_size_y_id") {
John Kessenichb9e39122016-08-17 10:22:08 -06004115 //publicType.shaderQualifiers.localSizeSpecId[1] = value;
4116 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004117 return;
4118 }
4119 if (id == "local_size_z_id") {
John Kessenichb9e39122016-08-17 10:22:08 -06004120 //publicType.shaderQualifiers.localSizeSpecId[2] = value;
4121 warn(loc, "ignored", id.c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004122 return;
4123 }
4124 }
4125 }
4126 break;
4127
4128 default:
4129 break;
4130 }
4131
4132 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
4133}
4134
4135// Merge any layout qualifier information from src into dst, leaving everything else in dst alone
4136//
4137// "More than one layout qualifier may appear in a single declaration.
4138// Additionally, the same layout-qualifier-name can occur multiple times
4139// within a layout qualifier or across multiple layout qualifiers in the
4140// same declaration. When the same layout-qualifier-name occurs
4141// multiple times, in a single declaration, the last occurrence overrides
4142// the former occurrence(s). Further, if such a layout-qualifier-name
4143// will effect subsequent declarations or other observable behavior, it
4144// is only the last occurrence that will have any effect, behaving as if
4145// the earlier occurrence(s) within the declaration are not present.
4146// This is also true for overriding layout-qualifier-names, where one
4147// overrides the other (e.g., row_major vs. column_major); only the last
4148// occurrence has any effect."
4149//
4150void HlslParseContext::mergeObjectLayoutQualifiers(TQualifier& dst, const TQualifier& src, bool inheritOnly)
4151{
4152 if (src.hasMatrix())
4153 dst.layoutMatrix = src.layoutMatrix;
4154 if (src.hasPacking())
4155 dst.layoutPacking = src.layoutPacking;
4156
4157 if (src.hasStream())
4158 dst.layoutStream = src.layoutStream;
4159
4160 if (src.hasFormat())
4161 dst.layoutFormat = src.layoutFormat;
4162
4163 if (src.hasXfbBuffer())
4164 dst.layoutXfbBuffer = src.layoutXfbBuffer;
4165
4166 if (src.hasAlign())
4167 dst.layoutAlign = src.layoutAlign;
4168
4169 if (! inheritOnly) {
4170 if (src.hasLocation())
4171 dst.layoutLocation = src.layoutLocation;
4172 if (src.hasComponent())
4173 dst.layoutComponent = src.layoutComponent;
4174 if (src.hasIndex())
4175 dst.layoutIndex = src.layoutIndex;
4176
4177 if (src.hasOffset())
4178 dst.layoutOffset = src.layoutOffset;
4179
4180 if (src.hasSet())
4181 dst.layoutSet = src.layoutSet;
4182 if (src.layoutBinding != TQualifier::layoutBindingEnd)
4183 dst.layoutBinding = src.layoutBinding;
4184
4185 if (src.hasXfbStride())
4186 dst.layoutXfbStride = src.layoutXfbStride;
4187 if (src.hasXfbOffset())
4188 dst.layoutXfbOffset = src.layoutXfbOffset;
4189 if (src.hasAttachment())
4190 dst.layoutAttachment = src.layoutAttachment;
4191 if (src.hasSpecConstantId())
4192 dst.layoutSpecConstantId = src.layoutSpecConstantId;
4193
4194 if (src.layoutPushConstant)
4195 dst.layoutPushConstant = true;
4196 }
4197}
4198
4199//
4200// Look up a function name in the symbol table, and make sure it is a function.
4201//
John Kessenichfcc0aa32016-08-24 18:34:43 -06004202// First, look for an exact match. If there is none, use the generic selector
4203// TParseContextBase::selectFunction() to find one, parameterized by the
4204// convertible() and better() predicates defined below.
4205//
John Kesseniche01a9bc2016-03-12 20:11:22 -07004206// Return the function symbol if found, otherwise nullptr.
4207//
4208const TFunction* HlslParseContext::findFunction(const TSourceLoc& loc, const TFunction& call, bool& builtIn)
4209{
John Kessenich7f349c72016-07-08 22:09:10 -06004210 // const TFunction* function = nullptr;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004211
4212 if (symbolTable.isFunctionNameVariable(call.getName())) {
4213 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
4214 return nullptr;
4215 }
4216
4217 // first, look for an exact match
4218 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
4219 if (symbol)
4220 return symbol->getAsFunction();
4221
John Kessenichfcc0aa32016-08-24 18:34:43 -06004222 // no exact match, use the generic selector, parameterized by the GLSL rules
John Kesseniche01a9bc2016-03-12 20:11:22 -07004223
John Kessenichfcc0aa32016-08-24 18:34:43 -06004224 // create list of candidates to send
John Kessenich0a04b4d2016-08-19 07:27:28 -06004225 TVector<const TFunction*> candidateList;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004226 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
John Kessenichfcc0aa32016-08-24 18:34:43 -06004227
4228 // can 'from' convert to 'to'?
John Kessenich81cd7642016-08-26 14:01:43 -06004229 const auto convertible = [this](const TType& from, const TType& to) {
John Kessenichfcc0aa32016-08-24 18:34:43 -06004230 if (from == to)
4231 return true;
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004232
4233 // no aggregate conversions
4234 if (from.isArray() || to.isArray() ||
4235 from.isStruct() || to.isStruct())
John Kessenichfcc0aa32016-08-24 18:34:43 -06004236 return false;
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004237
4238 // basic types have to be convertible
4239 if (! intermediate.canImplicitlyPromote(from.getBasicType(), to.getBasicType(), EOpFunctionCall))
4240 return false;
4241
4242 // shapes have to be convertible
4243 if ((from.isScalar() && to.isScalar()) ||
4244 (from.isScalar() && to.isVector()) ||
4245 (from.isVector() && to.isVector() && from.getVectorSize() >= to.getVectorSize()))
4246 return true;
4247
4248 // TODO: what are the matrix rules? they go here
4249
4250 return false;
John Kessenichfcc0aa32016-08-24 18:34:43 -06004251 };
John Kesseniche01a9bc2016-03-12 20:11:22 -07004252
John Kessenichfcc0aa32016-08-24 18:34:43 -06004253 // Is 'to2' a better conversion than 'to1'?
4254 // Ties should not be considered as better.
4255 // Assumes 'convertible' already said true.
John Kessenich81cd7642016-08-26 14:01:43 -06004256 const auto better = [](const TType& from, const TType& to1, const TType& to2) {
John Kessenich90dd70f2016-08-25 10:49:21 -06004257 // exact match is always better than mismatch
John Kessenichfcc0aa32016-08-24 18:34:43 -06004258 if (from == to2)
4259 return from != to1;
4260 if (from == to1)
4261 return false;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004262
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004263 // shape changes are always worse
4264 if (from.isScalar() || from.isVector()) {
4265 if (from.getVectorSize() == to2.getVectorSize() &&
4266 from.getVectorSize() != to1.getVectorSize())
John Kessenichfcc0aa32016-08-24 18:34:43 -06004267 return true;
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004268 if (from.getVectorSize() == to1.getVectorSize() &&
4269 from.getVectorSize() != to2.getVectorSize())
4270 return false;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004271 }
John Kesseniche01a9bc2016-03-12 20:11:22 -07004272
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004273 // Might or might not be changing shape, which means basic type might
4274 // or might not match, so within that, the question is how big a
4275 // basic-type conversion is being done.
4276 //
4277 // Use a hierarchy of domains, translated to order of magnitude
4278 // in a linearized view:
4279 // - floating-point vs. integer
4280 // - 32 vs. 64 bit (or width in general)
4281 // - bool vs. non bool
4282 // - signed vs. not signed
John Kessenich81cd7642016-08-26 14:01:43 -06004283 const auto linearize = [](const TBasicType& basicType) {
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004284 switch (basicType) {
4285 case EbtBool: return 1;
4286 case EbtInt: return 10;
4287 case EbtUint: return 11;
4288 case EbtInt64: return 20;
4289 case EbtUint64: return 21;
4290 case EbtFloat: return 100;
4291 case EbtDouble: return 110;
4292 default: return 0;
4293 }
4294 };
John Kessenich90dd70f2016-08-25 10:49:21 -06004295
John Kesseniche3f2c8f2016-08-25 15:57:56 -06004296 return std::abs(linearize(to2.getBasicType()) - linearize(from.getBasicType())) <
4297 std::abs(linearize(to1.getBasicType()) - linearize(from.getBasicType()));
John Kessenichfcc0aa32016-08-24 18:34:43 -06004298 };
4299
4300 // for ambiguity reporting
4301 bool tie = false;
4302
4303 // send to the generic selector
4304 const TFunction* bestMatch = selectFunction(candidateList, call, convertible, better, tie);
4305
4306 if (bestMatch == nullptr)
John Kesseniche01a9bc2016-03-12 20:11:22 -07004307 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
John Kessenichfcc0aa32016-08-24 18:34:43 -06004308 else if (tie)
4309 error(loc, "ambiguous best function under implicit type conversion", call.getName().c_str(), "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004310
John Kessenichfcc0aa32016-08-24 18:34:43 -06004311 return bestMatch;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004312}
4313
4314//
John Kessenich5e69ec62016-07-05 00:02:40 -06004315// Do everything necessary to handle a typedef declaration, for a single symbol.
4316//
4317// 'parseType' is the type part of the declaration (to the left)
4318// 'arraySizes' is the arrayness tagged on the identifier (to the right)
4319//
Alex Szpakowski49ad2b72016-10-08 22:07:20 -03004320void HlslParseContext::declareTypedef(const TSourceLoc& loc, TString& identifier, const TType& parseType, TArraySizes* /*arraySizes*/)
John Kessenich5e69ec62016-07-05 00:02:40 -06004321{
4322 TType type;
4323 type.deepCopy(parseType);
4324
John Kessenich5e69ec62016-07-05 00:02:40 -06004325 TVariable* typeSymbol = new TVariable(&identifier, type, true);
4326 if (! symbolTable.insert(*typeSymbol))
4327 error(loc, "name already defined", "typedef", identifier.c_str());
4328}
4329
4330//
John Kesseniche01a9bc2016-03-12 20:11:22 -07004331// Do everything necessary to handle a variable (non-block) declaration.
4332// Either redeclaring a variable, or making a new one, updating the symbol
4333// table, and all error checking.
4334//
4335// Returns a subtree node that computes an initializer, if needed.
4336// Returns nullptr if there is no code to execute for initialization.
4337//
John Kessenich5e69ec62016-07-05 00:02:40 -06004338// 'parseType' is the type part of the declaration (to the left)
John Kesseniche01a9bc2016-03-12 20:11:22 -07004339// 'arraySizes' is the arrayness tagged on the identifier (to the right)
4340//
John Kesseniche82061d2016-09-27 14:38:57 -06004341TIntermNode* HlslParseContext::declareVariable(const TSourceLoc& loc, TString& identifier, TType& type, TIntermTyped* initializer)
John Kesseniche01a9bc2016-03-12 20:11:22 -07004342{
John Kesseniche01a9bc2016-03-12 20:11:22 -07004343 if (voidErrorCheck(loc, identifier, type.getBasicType()))
4344 return nullptr;
4345
4346 // Check for redeclaration of built-ins and/or attempting to declare a reserved name
4347 bool newDeclaration = false; // true if a new entry gets added to the symbol table
John Kessenich5e69ec62016-07-05 00:02:40 -06004348 TSymbol* symbol = nullptr; // = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), parseType.shaderQualifiers, newDeclaration);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004349
4350 inheritGlobalDefaults(type.getQualifier());
4351
steve-lunarge0b9deb2016-09-16 13:26:37 -06004352 bool flattenVar = false;
4353
John Kesseniche01a9bc2016-03-12 20:11:22 -07004354 // Declare the variable
John Kesseniche82061d2016-09-27 14:38:57 -06004355 if (type.isArray()) {
4356 // array case
John Kesseniche01a9bc2016-03-12 20:11:22 -07004357 declareArray(loc, identifier, type, symbol, newDeclaration);
steve-lunarge0b9deb2016-09-16 13:26:37 -06004358 flattenVar = shouldFlatten(type);
steve-lunarge0b9deb2016-09-16 13:26:37 -06004359 if (flattenVar)
4360 flatten(loc, *symbol->getAsVariable());
John Kesseniche01a9bc2016-03-12 20:11:22 -07004361 } else {
4362 // non-array case
4363 if (! symbol)
4364 symbol = declareNonArray(loc, identifier, type, newDeclaration);
4365 else if (type != symbol->getType())
4366 error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
4367 }
4368
4369 if (! symbol)
4370 return nullptr;
4371
4372 // Deal with initializer
4373 TIntermNode* initNode = nullptr;
4374 if (symbol && initializer) {
steve-lunarge0b9deb2016-09-16 13:26:37 -06004375 if (flattenVar)
4376 error(loc, "flattened array with initializer list unsupported", identifier.c_str(), "");
4377
John Kesseniche01a9bc2016-03-12 20:11:22 -07004378 TVariable* variable = symbol->getAsVariable();
4379 if (! variable) {
4380 error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
4381 return nullptr;
4382 }
4383 initNode = executeInitializer(loc, initializer, variable);
4384 }
4385
steve-lunarge0b9deb2016-09-16 13:26:37 -06004386 // see if it's a linker-level object to track. if it's flattened above,
4387 // that process added linkage objects for the flattened symbols, we don't
4388 // add the aggregate here.
4389 if (!flattenVar)
4390 if (newDeclaration && symbolTable.atGlobalLevel())
4391 intermediate.addSymbolLinkageNode(linkage, *symbol);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004392
4393 return initNode;
4394}
4395
4396// Pick up global defaults from the provide global defaults into dst.
4397void HlslParseContext::inheritGlobalDefaults(TQualifier& dst) const
4398{
4399 if (dst.storage == EvqVaryingOut) {
4400 if (! dst.hasStream() && language == EShLangGeometry)
4401 dst.layoutStream = globalOutputDefaults.layoutStream;
4402 if (! dst.hasXfbBuffer())
4403 dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
4404 }
4405}
4406
4407//
4408// Make an internal-only variable whose name is for debug purposes only
4409// and won't be searched for. Callers will only use the return value to use
4410// the variable, not the name to look it up. It is okay if the name
4411// is the same as other names; there won't be any conflict.
4412//
4413TVariable* HlslParseContext::makeInternalVariable(const char* name, const TType& type) const
4414{
4415 TString* nameString = new TString(name);
4416 TVariable* variable = new TVariable(nameString, type);
4417 symbolTable.makeInternalVariable(*variable);
4418
4419 return variable;
4420}
4421
4422//
4423// Declare a non-array variable, the main point being there is no redeclaration
4424// for resizing allowed.
4425//
4426// Return the successfully declared variable.
4427//
4428TVariable* HlslParseContext::declareNonArray(const TSourceLoc& loc, TString& identifier, TType& type, bool& newDeclaration)
4429{
4430 // make a new variable
4431 TVariable* variable = new TVariable(&identifier, type);
4432
4433 // add variable to symbol table
4434 if (! symbolTable.insert(*variable)) {
4435 error(loc, "redefinition", variable->getName().c_str(), "");
4436 return nullptr;
4437 } else {
4438 newDeclaration = true;
4439 return variable;
4440 }
4441}
4442
4443//
4444// Handle all types of initializers from the grammar.
4445//
4446// Returning nullptr just means there is no code to execute to handle the
4447// initializer, which will, for example, be the case for constant initializers.
4448//
4449TIntermNode* HlslParseContext::executeInitializer(const TSourceLoc& loc, TIntermTyped* initializer, TVariable* variable)
4450{
4451 //
4452 // Identifier must be of type constant, a global, or a temporary, and
4453 // starting at version 120, desktop allows uniforms to have initializers.
4454 //
4455 TStorageQualifier qualifier = variable->getType().getQualifier().storage;
4456
4457 //
4458 // If the initializer was from braces { ... }, we convert the whole subtree to a
4459 // constructor-style subtree, allowing the rest of the code to operate
4460 // identically for both kinds of initializers.
4461 //
4462 initializer = convertInitializerList(loc, variable->getType(), initializer);
4463 if (! initializer) {
4464 // error recovery; don't leave const without constant values
4465 if (qualifier == EvqConst)
4466 variable->getWritableType().getQualifier().storage = EvqTemporary;
4467 return nullptr;
4468 }
4469
4470 // Fix outer arrayness if variable is unsized, getting size from the initializer
4471 if (initializer->getType().isExplicitlySizedArray() &&
4472 variable->getType().isImplicitlySizedArray())
4473 variable->getWritableType().changeOuterArraySize(initializer->getType().getOuterArraySize());
4474
4475 // Inner arrayness can also get set by an initializer
4476 if (initializer->getType().isArrayOfArrays() && variable->getType().isArrayOfArrays() &&
4477 initializer->getType().getArraySizes()->getNumDims() ==
4478 variable->getType().getArraySizes()->getNumDims()) {
4479 // adopt unsized sizes from the initializer's sizes
4480 for (int d = 1; d < variable->getType().getArraySizes()->getNumDims(); ++d) {
4481 if (variable->getType().getArraySizes()->getDimSize(d) == UnsizedArraySize)
4482 variable->getWritableType().getArraySizes().setDimSize(d, initializer->getType().getArraySizes()->getDimSize(d));
4483 }
4484 }
4485
4486 // Uniform and global consts require a constant initializer
4487 if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
4488 error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
4489 variable->getWritableType().getQualifier().storage = EvqTemporary;
4490 return nullptr;
4491 }
4492 if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
4493 error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
4494 variable->getWritableType().getQualifier().storage = EvqTemporary;
4495 return nullptr;
4496 }
4497
4498 // Const variables require a constant initializer, depending on version
4499 if (qualifier == EvqConst) {
4500 if (initializer->getType().getQualifier().storage != EvqConst) {
4501 variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
4502 qualifier = EvqConstReadOnly;
4503 }
4504 }
4505
4506 if (qualifier == EvqConst || qualifier == EvqUniform) {
4507 // Compile-time tagging of the variable with its constant value...
4508
4509 initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
4510 if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
4511 error(loc, "non-matching or non-convertible constant type for const initializer",
4512 variable->getType().getStorageQualifierString(), "");
4513 variable->getWritableType().getQualifier().storage = EvqTemporary;
4514 return nullptr;
4515 }
4516
4517 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
4518 } else {
4519 // normal assigning of a value to a variable...
4520 specializationCheck(loc, initializer->getType(), "initializer");
4521 TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
steve-lunarge0b9deb2016-09-16 13:26:37 -06004522 TIntermNode* initNode = handleAssign(loc, EOpAssign, intermSymbol, initializer);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004523 if (! initNode)
4524 assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
4525
4526 return initNode;
4527 }
4528
4529 return nullptr;
4530}
4531
4532//
4533// Reprocess any initializer-list { ... } parts of the initializer.
4534// Need to hierarchically assign correct types and implicit
4535// conversions. Will do this mimicking the same process used for
4536// creating a constructor-style initializer, ensuring we get the
4537// same form.
4538//
4539TIntermTyped* HlslParseContext::convertInitializerList(const TSourceLoc& loc, const TType& type, TIntermTyped* initializer)
4540{
4541 // Will operate recursively. Once a subtree is found that is constructor style,
4542 // everything below it is already good: Only the "top part" of the initializer
4543 // can be an initializer list, where "top part" can extend for several (or all) levels.
4544
4545 // see if we have bottomed out in the tree within the initializer-list part
4546 TIntermAggregate* initList = initializer->getAsAggregate();
4547 if (! initList || initList->getOp() != EOpNull)
4548 return initializer;
4549
4550 // Of the initializer-list set of nodes, need to process bottom up,
4551 // so recurse deep, then process on the way up.
4552
4553 // Go down the tree here...
4554 if (type.isArray()) {
4555 // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
4556 // Later on, initializer execution code will deal with array size logic.
4557 TType arrayType;
4558 arrayType.shallowCopy(type); // sharing struct stuff is fine
4559 arrayType.newArraySizes(*type.getArraySizes()); // but get a fresh copy of the array information, to edit below
4560
4561 // edit array sizes to fill in unsized dimensions
4562 arrayType.changeOuterArraySize((int)initList->getSequence().size());
4563 TIntermTyped* firstInit = initList->getSequence()[0]->getAsTyped();
4564 if (arrayType.isArrayOfArrays() && firstInit->getType().isArray() &&
4565 arrayType.getArraySizes().getNumDims() == firstInit->getType().getArraySizes()->getNumDims() + 1) {
4566 for (int d = 1; d < arrayType.getArraySizes().getNumDims(); ++d) {
4567 if (arrayType.getArraySizes().getDimSize(d) == UnsizedArraySize)
4568 arrayType.getArraySizes().setDimSize(d, firstInit->getType().getArraySizes()->getDimSize(d - 1));
4569 }
4570 }
4571
4572 TType elementType(arrayType, 0); // dereferenced type
4573 for (size_t i = 0; i < initList->getSequence().size(); ++i) {
4574 initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
4575 if (initList->getSequence()[i] == nullptr)
4576 return nullptr;
4577 }
4578
John Kessenicha26a5172016-07-28 15:29:35 -06004579 return addConstructor(loc, initList, arrayType);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004580 } else if (type.isStruct()) {
4581 if (type.getStruct()->size() != initList->getSequence().size()) {
4582 error(loc, "wrong number of structure members", "initializer list", "");
4583 return nullptr;
4584 }
4585 for (size_t i = 0; i < type.getStruct()->size(); ++i) {
4586 initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
4587 if (initList->getSequence()[i] == nullptr)
4588 return nullptr;
4589 }
4590 } else if (type.isMatrix()) {
steve-lunarg297ae212016-08-24 14:36:13 -06004591 if (type.computeNumComponents() == (int)initList->getSequence().size()) {
4592 // This means the matrix is initialized component-wise, rather than as
4593 // a series of rows and columns. We can just use the list directly as
4594 // a constructor; no further processing needed.
4595 } else {
4596 if (type.getMatrixCols() != (int)initList->getSequence().size()) {
4597 error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
John Kesseniche01a9bc2016-03-12 20:11:22 -07004598 return nullptr;
steve-lunarg297ae212016-08-24 14:36:13 -06004599 }
4600 TType vectorType(type, 0); // dereferenced type
4601 for (int i = 0; i < type.getMatrixCols(); ++i) {
4602 initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
4603 if (initList->getSequence()[i] == nullptr)
4604 return nullptr;
4605 }
John Kesseniche01a9bc2016-03-12 20:11:22 -07004606 }
4607 } else if (type.isVector()) {
4608 if (type.getVectorSize() != (int)initList->getSequence().size()) {
4609 error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
4610 return nullptr;
4611 }
steve-lunargfe5a3ff2016-07-30 10:36:09 -06004612 } else if (type.isScalar()) {
4613 if ((int)initList->getSequence().size() != 1) {
4614 error(loc, "scalar expected one element:", "initializer list", type.getCompleteString().c_str());
4615 return nullptr;
4616 }
4617 } else {
John Kesseniche01a9bc2016-03-12 20:11:22 -07004618 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
4619 return nullptr;
4620 }
4621
John Kessenichff132132016-07-29 18:22:22 -06004622 // Now that the subtree is processed, process this node as if the
4623 // initializer list is a set of arguments to a constructor.
4624 TIntermNode* emulatedConstructorArguments;
4625 if (initList->getSequence().size() == 1)
4626 emulatedConstructorArguments = initList->getSequence()[0];
4627 else
4628 emulatedConstructorArguments = initList;
4629 return addConstructor(loc, emulatedConstructorArguments, type);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004630}
4631
4632//
4633// Test for the correctness of the parameters passed to various constructor functions
4634// and also convert them to the right data type, if allowed and required.
4635//
4636// Returns nullptr for an error or the constructed node (aggregate or typed) for no error.
4637//
John Kessenicha26a5172016-07-28 15:29:35 -06004638TIntermTyped* HlslParseContext::addConstructor(const TSourceLoc& loc, TIntermNode* node, const TType& type)
John Kesseniche01a9bc2016-03-12 20:11:22 -07004639{
4640 if (node == nullptr || node->getAsTyped() == nullptr)
4641 return nullptr;
4642
4643 TIntermAggregate* aggrNode = node->getAsAggregate();
John Kessenicha26a5172016-07-28 15:29:35 -06004644 TOperator op = intermediate.mapTypeToConstructorOp(type);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004645
4646 // Combined texture-sampler constructors are completely semantic checked
4647 // in constructorTextureSamplerError()
4648 if (op == EOpConstructTextureSampler)
4649 return intermediate.setAggregateOperator(aggrNode, op, type, loc);
4650
4651 TTypeList::const_iterator memberTypes;
4652 if (op == EOpConstructStruct)
4653 memberTypes = type.getStruct()->begin();
4654
4655 TType elementType;
4656 if (type.isArray()) {
4657 TType dereferenced(type, 0);
4658 elementType.shallowCopy(dereferenced);
4659 } else
4660 elementType.shallowCopy(type);
4661
4662 bool singleArg;
4663 if (aggrNode) {
4664 if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
4665 singleArg = true;
4666 else
4667 singleArg = false;
4668 } else
4669 singleArg = true;
4670
4671 TIntermTyped *newNode;
4672 if (singleArg) {
4673 // If structure constructor or array constructor is being called
4674 // for only one parameter inside the structure, we need to call constructAggregate function once.
4675 if (type.isArray())
4676 newNode = constructAggregate(node, elementType, 1, node->getLoc());
4677 else if (op == EOpConstructStruct)
4678 newNode = constructAggregate(node, *(*memberTypes).type, 1, node->getLoc());
4679 else
4680 newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
4681
4682 if (newNode && (type.isArray() || op == EOpConstructStruct))
4683 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
4684
4685 return newNode;
4686 }
4687
4688 //
4689 // Handle list of arguments.
4690 //
4691 TIntermSequence &sequenceVector = aggrNode->getSequence(); // Stores the information about the parameter to the constructor
4692 // if the structure constructor contains more than one parameter, then construct
4693 // each parameter
4694
4695 int paramCount = 0; // keeps a track of the constructor parameter number being checked
4696
4697 // for each parameter to the constructor call, check to see if the right type is passed or convert them
4698 // to the right type if possible (and allowed).
4699 // for structure constructors, just check if the right type is passed, no conversion is allowed.
4700
4701 for (TIntermSequence::iterator p = sequenceVector.begin();
4702 p != sequenceVector.end(); p++, paramCount++) {
4703 if (type.isArray())
4704 newNode = constructAggregate(*p, elementType, paramCount + 1, node->getLoc());
4705 else if (op == EOpConstructStruct)
4706 newNode = constructAggregate(*p, *(memberTypes[paramCount]).type, paramCount + 1, node->getLoc());
4707 else
4708 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
4709
4710 if (newNode)
4711 *p = newNode;
4712 else
4713 return nullptr;
4714 }
4715
4716 TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
4717
4718 return constructor;
4719}
4720
4721// Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
4722// for the parameter to the constructor (passed to this function). Essentially, it converts
4723// the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
4724// float, then float is converted to int.
4725//
4726// Returns nullptr for an error or the constructed node.
4727//
4728TIntermTyped* HlslParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, const TSourceLoc& loc, bool subset)
4729{
4730 TIntermTyped* newNode;
4731 TOperator basicOp;
4732
4733 //
4734 // First, convert types as needed.
4735 //
4736 switch (op) {
4737 case EOpConstructVec2:
4738 case EOpConstructVec3:
4739 case EOpConstructVec4:
4740 case EOpConstructMat2x2:
4741 case EOpConstructMat2x3:
4742 case EOpConstructMat2x4:
4743 case EOpConstructMat3x2:
4744 case EOpConstructMat3x3:
4745 case EOpConstructMat3x4:
4746 case EOpConstructMat4x2:
4747 case EOpConstructMat4x3:
4748 case EOpConstructMat4x4:
4749 case EOpConstructFloat:
4750 basicOp = EOpConstructFloat;
4751 break;
4752
4753 case EOpConstructDVec2:
4754 case EOpConstructDVec3:
4755 case EOpConstructDVec4:
4756 case EOpConstructDMat2x2:
4757 case EOpConstructDMat2x3:
4758 case EOpConstructDMat2x4:
4759 case EOpConstructDMat3x2:
4760 case EOpConstructDMat3x3:
4761 case EOpConstructDMat3x4:
4762 case EOpConstructDMat4x2:
4763 case EOpConstructDMat4x3:
4764 case EOpConstructDMat4x4:
4765 case EOpConstructDouble:
4766 basicOp = EOpConstructDouble;
4767 break;
4768
4769 case EOpConstructIVec2:
4770 case EOpConstructIVec3:
4771 case EOpConstructIVec4:
4772 case EOpConstructInt:
4773 basicOp = EOpConstructInt;
4774 break;
4775
4776 case EOpConstructUVec2:
4777 case EOpConstructUVec3:
4778 case EOpConstructUVec4:
4779 case EOpConstructUint:
4780 basicOp = EOpConstructUint;
4781 break;
4782
4783 case EOpConstructBVec2:
4784 case EOpConstructBVec3:
4785 case EOpConstructBVec4:
4786 case EOpConstructBool:
4787 basicOp = EOpConstructBool;
4788 break;
4789
4790 default:
4791 error(loc, "unsupported construction", "", "");
4792
4793 return nullptr;
4794 }
4795 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
4796 if (newNode == nullptr) {
4797 error(loc, "can't convert", "constructor", "");
4798 return nullptr;
4799 }
4800
4801 //
4802 // Now, if there still isn't an operation to do the construction, and we need one, add one.
4803 //
4804
4805 // Otherwise, skip out early.
4806 if (subset || (newNode != node && newNode->getType() == type))
4807 return newNode;
4808
4809 // setAggregateOperator will insert a new node for the constructor, as needed.
4810 return intermediate.setAggregateOperator(newNode, op, type, loc);
4811}
4812
4813// This function tests for the type of the parameters to the structure or array constructor. Raises
4814// an error message if the expected type does not match the parameter passed to the constructor.
4815//
4816// Returns nullptr for an error or the input node itself if the expected and the given parameter types match.
4817//
4818TIntermTyped* HlslParseContext::constructAggregate(TIntermNode* node, const TType& type, int paramCount, const TSourceLoc& loc)
4819{
4820 TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
4821 if (! converted || converted->getType() != type) {
4822 error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
4823 node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
4824
4825 return nullptr;
4826 }
4827
4828 return converted;
4829}
4830
4831//
4832// Do everything needed to add an interface block.
4833//
John Kessenich3d157c52016-07-25 16:05:33 -06004834void HlslParseContext::declareBlock(const TSourceLoc& loc, TType& type, const TString* instanceName, TArraySizes* arraySizes)
John Kesseniche01a9bc2016-03-12 20:11:22 -07004835{
John Kessenich3d157c52016-07-25 16:05:33 -06004836 assert(type.getWritableStruct() != nullptr);
4837
4838 TTypeList& typeList = *type.getWritableStruct();
John Kesseniche01a9bc2016-03-12 20:11:22 -07004839 // fix and check for member storage qualifiers and types that don't belong within a block
4840 for (unsigned int member = 0; member < typeList.size(); ++member) {
4841 TType& memberType = *typeList[member].type;
4842 TQualifier& memberQualifier = memberType.getQualifier();
4843 const TSourceLoc& memberLoc = typeList[member].loc;
4844 globalQualifierFix(memberLoc, memberQualifier);
John Kessenich3d157c52016-07-25 16:05:33 -06004845 memberQualifier.storage = type.getQualifier().storage;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004846 }
4847
4848 // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
4849 // do all the rest.
John Kessenich3d157c52016-07-25 16:05:33 -06004850 //if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
4851 // redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
4852 // return;
4853 //}
John Kesseniche01a9bc2016-03-12 20:11:22 -07004854
4855 // Make default block qualification, and adjust the member qualifications
4856
4857 TQualifier defaultQualification;
John Kessenich3d157c52016-07-25 16:05:33 -06004858 switch (type.getQualifier().storage) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07004859 case EvqUniform: defaultQualification = globalUniformDefaults; break;
4860 case EvqBuffer: defaultQualification = globalBufferDefaults; break;
4861 case EvqVaryingIn: defaultQualification = globalInputDefaults; break;
4862 case EvqVaryingOut: defaultQualification = globalOutputDefaults; break;
4863 default: defaultQualification.clear(); break;
4864 }
4865
4866 // Special case for "push_constant uniform", which has a default of std430,
4867 // contrary to normal uniform defaults, and can't have a default tracked for it.
John Kessenich3d157c52016-07-25 16:05:33 -06004868 if (type.getQualifier().layoutPushConstant && ! type.getQualifier().hasPacking())
4869 type.getQualifier().layoutPacking = ElpStd430;
John Kesseniche01a9bc2016-03-12 20:11:22 -07004870
4871 // fix and check for member layout qualifiers
4872
John Kessenich3d157c52016-07-25 16:05:33 -06004873 mergeObjectLayoutQualifiers(defaultQualification, type.getQualifier(), true);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004874
4875 bool memberWithLocation = false;
4876 bool memberWithoutLocation = false;
4877 for (unsigned int member = 0; member < typeList.size(); ++member) {
4878 TQualifier& memberQualifier = typeList[member].type->getQualifier();
4879 const TSourceLoc& memberLoc = typeList[member].loc;
4880 if (memberQualifier.hasStream()) {
4881 if (defaultQualification.layoutStream != memberQualifier.layoutStream)
4882 error(memberLoc, "member cannot contradict block", "stream", "");
4883 }
4884
4885 // "This includes a block's inheritance of the
4886 // current global default buffer, a block member's inheritance of the block's
4887 // buffer, and the requirement that any *xfb_buffer* declared on a block
4888 // member must match the buffer inherited from the block."
4889 if (memberQualifier.hasXfbBuffer()) {
4890 if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
4891 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4892 }
4893
4894 if (memberQualifier.hasPacking())
4895 error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
4896 if (memberQualifier.hasLocation()) {
John Kessenich3d157c52016-07-25 16:05:33 -06004897 switch (type.getQualifier().storage) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07004898 case EvqVaryingIn:
4899 case EvqVaryingOut:
4900 memberWithLocation = true;
4901 break;
4902 default:
4903 break;
4904 }
4905 } else
4906 memberWithoutLocation = true;
4907 if (memberQualifier.hasAlign()) {
4908 if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
4909 error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
4910 }
4911
4912 TQualifier newMemberQualification = defaultQualification;
John Kessenich34e7ee72016-09-16 17:10:39 -06004913 mergeQualifiers(newMemberQualification, memberQualifier);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004914 memberQualifier = newMemberQualification;
4915 }
4916
4917 // Process the members
John Kessenich3d157c52016-07-25 16:05:33 -06004918 fixBlockLocations(loc, type.getQualifier(), typeList, memberWithLocation, memberWithoutLocation);
4919 fixBlockXfbOffsets(type.getQualifier(), typeList);
4920 fixBlockUniformOffsets(type.getQualifier(), typeList);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004921
4922 // reverse merge, so that currentBlockQualifier now has all layout information
4923 // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
John Kessenich3d157c52016-07-25 16:05:33 -06004924 mergeObjectLayoutQualifiers(type.getQualifier(), defaultQualification, true);
John Kesseniche01a9bc2016-03-12 20:11:22 -07004925
4926 //
4927 // Build and add the interface block as a new type named 'blockName'
4928 //
4929
steve-lunarg8ffc36a2016-09-21 14:19:40 -06004930 // Use the instance name as the interface name if one exists, else the block name.
4931 const TString& interfaceName = (instanceName && !instanceName->empty()) ? *instanceName : type.getTypeName();
4932
4933 TType blockType(&typeList, interfaceName, type.getQualifier());
John Kesseniche01a9bc2016-03-12 20:11:22 -07004934 if (arraySizes)
4935 blockType.newArraySizes(*arraySizes);
4936
John Kesseniche01a9bc2016-03-12 20:11:22 -07004937 // Add the variable, as anonymous or named instanceName.
4938 // Make an anonymous variable if no name was provided.
4939 if (! instanceName)
4940 instanceName = NewPoolTString("");
4941
4942 TVariable& variable = *new TVariable(instanceName, blockType);
4943 if (! symbolTable.insert(variable)) {
4944 if (*instanceName == "")
John Kessenich3d157c52016-07-25 16:05:33 -06004945 error(loc, "nameless block contains a member that already has a name at global scope", "" /* blockName->c_str() */, "");
John Kesseniche01a9bc2016-03-12 20:11:22 -07004946 else
4947 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
4948
4949 return;
4950 }
4951
John Kesseniche01a9bc2016-03-12 20:11:22 -07004952 // Save it in the AST for linker use.
4953 intermediate.addSymbolLinkageNode(linkage, variable);
4954}
4955
John Kessenich6dbc0a72016-09-27 19:13:05 -06004956void HlslParseContext::finalizeGlobalUniformBlockLayout(TVariable& block)
4957{
4958 block.getWritableType().getQualifier().layoutPacking = ElpStd140;
4959 block.getWritableType().getQualifier().layoutMatrix = ElmRowMajor;
4960 fixBlockUniformOffsets(block.getType().getQualifier(), *block.getWritableType().getWritableStruct());
4961}
4962
John Kesseniche01a9bc2016-03-12 20:11:22 -07004963//
4964// "For a block, this process applies to the entire block, or until the first member
4965// is reached that has a location layout qualifier. When a block member is declared with a location
4966// qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
4967// declaration. Subsequent members are again assigned consecutive locations, based on the newest location,
4968// until the next member declared with a location qualifier. The values used for locations do not have to be
4969// declared in increasing order."
4970void HlslParseContext::fixBlockLocations(const TSourceLoc& loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
4971{
4972 // "If a block has no block-level location layout qualifier, it is required that either all or none of its members
4973 // have a location layout qualifier, or a compile-time error results."
4974 if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
4975 error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
4976 else {
4977 if (memberWithLocation) {
4978 // remove any block-level location and make it per *every* member
4979 int nextLocation = 0; // by the rule above, initial value is not relevant
4980 if (qualifier.hasAnyLocation()) {
4981 nextLocation = qualifier.layoutLocation;
4982 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
4983 if (qualifier.hasComponent()) {
4984 // "It is a compile-time error to apply the *component* qualifier to a ... block"
4985 error(loc, "cannot apply to a block", "component", "");
4986 }
4987 if (qualifier.hasIndex()) {
4988 error(loc, "cannot apply to a block", "index", "");
4989 }
4990 }
4991 for (unsigned int member = 0; member < typeList.size(); ++member) {
4992 TQualifier& memberQualifier = typeList[member].type->getQualifier();
4993 const TSourceLoc& memberLoc = typeList[member].loc;
4994 if (! memberQualifier.hasLocation()) {
4995 if (nextLocation >= (int)TQualifier::layoutLocationEnd)
4996 error(memberLoc, "location is too large", "location", "");
4997 memberQualifier.layoutLocation = nextLocation;
4998 memberQualifier.layoutComponent = 0;
4999 }
5000 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
5001 }
5002 }
5003 }
5004}
5005
5006void HlslParseContext::fixBlockXfbOffsets(TQualifier& qualifier, TTypeList& typeList)
5007{
5008 // "If a block is qualified with xfb_offset, all its
5009 // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any
5010 // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer
5011 // offsets."
5012
5013 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
5014 return;
5015
5016 int nextOffset = qualifier.layoutXfbOffset;
5017 for (unsigned int member = 0; member < typeList.size(); ++member) {
5018 TQualifier& memberQualifier = typeList[member].type->getQualifier();
5019 bool containsDouble = false;
5020 int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
5021 // see if we need to auto-assign an offset to this member
5022 if (! memberQualifier.hasXfbOffset()) {
5023 // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
5024 if (containsDouble)
5025 RoundToPow2(nextOffset, 8);
5026 memberQualifier.layoutXfbOffset = nextOffset;
5027 } else
5028 nextOffset = memberQualifier.layoutXfbOffset;
5029 nextOffset += memberSize;
5030 }
5031
5032 // The above gave all block members an offset, so we can take it off the block now,
5033 // which will avoid double counting the offset usage.
5034 qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
5035}
5036
5037// Calculate and save the offset of each block member, using the recursively
5038// defined block offset rules and the user-provided offset and align.
5039//
5040// Also, compute and save the total size of the block. For the block's size, arrayness
5041// is not taken into account, as each element is backed by a separate buffer.
5042//
John Kessenich6dbc0a72016-09-27 19:13:05 -06005043void HlslParseContext::fixBlockUniformOffsets(const TQualifier& qualifier, TTypeList& typeList)
John Kesseniche01a9bc2016-03-12 20:11:22 -07005044{
5045 if (! qualifier.isUniformOrBuffer())
5046 return;
5047 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
5048 return;
5049
5050 int offset = 0;
5051 int memberSize;
5052 for (unsigned int member = 0; member < typeList.size(); ++member) {
5053 TQualifier& memberQualifier = typeList[member].type->getQualifier();
5054 const TSourceLoc& memberLoc = typeList[member].loc;
5055
5056 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
5057
5058 // modify just the children's view of matrix layout, if there is one for this member
5059 TLayoutMatrix subMatrixLayout = typeList[member].type->getQualifier().layoutMatrix;
5060 int dummyStride;
John Kessenich6dbc0a72016-09-27 19:13:05 -06005061 int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, dummyStride,
5062 qualifier.layoutPacking == ElpStd140,
5063 subMatrixLayout != ElmNone ? subMatrixLayout == ElmRowMajor
5064 : qualifier.layoutMatrix == ElmRowMajor);
John Kesseniche01a9bc2016-03-12 20:11:22 -07005065 if (memberQualifier.hasOffset()) {
5066 // "The specified offset must be a multiple
5067 // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
5068 if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
5069 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
5070
John Kesseniche01a9bc2016-03-12 20:11:22 -07005071 // "The offset qualifier forces the qualified member to start at or after the specified
5072 // integral-constant expression, which will be its byte offset from the beginning of the buffer.
5073 // "The actual offset of a member is computed as
5074 // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
5075 offset = std::max(offset, memberQualifier.layoutOffset);
5076 }
5077
5078 // "The actual alignment of a member will be the greater of the specified align alignment and the standard
5079 // (e.g., std140) base alignment for the member's type."
5080 if (memberQualifier.hasAlign())
5081 memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
5082
5083 // "If the resulting offset is not a multiple of the actual alignment,
5084 // increase it to the first offset that is a multiple of
5085 // the actual alignment."
5086 RoundToPow2(offset, memberAlignment);
5087 typeList[member].type->getQualifier().layoutOffset = offset;
5088 offset += memberSize;
5089 }
5090}
5091
5092// For an identifier that is already declared, add more qualification to it.
5093void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, const TString& identifier)
5094{
5095 TSymbol* symbol = symbolTable.find(identifier);
5096 if (! symbol) {
5097 error(loc, "identifier not previously declared", identifier.c_str(), "");
5098 return;
5099 }
5100 if (symbol->getAsFunction()) {
5101 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
5102 return;
5103 }
5104
5105 if (qualifier.isAuxiliary() ||
5106 qualifier.isMemory() ||
5107 qualifier.isInterpolation() ||
5108 qualifier.hasLayout() ||
5109 qualifier.storage != EvqTemporary ||
5110 qualifier.precision != EpqNone) {
5111 error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
5112 return;
5113 }
5114
5115 // For read-only built-ins, add a new symbol for holding the modified qualifier.
5116 // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
5117 if (symbol->isReadOnly())
5118 symbol = symbolTable.copyUp(symbol);
5119
5120 if (qualifier.invariant) {
5121 if (intermediate.inIoAccessed(identifier))
5122 error(loc, "cannot change qualification after use", "invariant", "");
5123 symbol->getWritableType().getQualifier().invariant = true;
John Kessenich17f07862016-05-04 12:36:14 -06005124 } else if (qualifier.noContraction) {
5125 if (intermediate.inIoAccessed(identifier))
5126 error(loc, "cannot change qualification after use", "precise", "");
5127 symbol->getWritableType().getQualifier().noContraction = true;
5128 } else if (qualifier.specConstant) {
5129 symbol->getWritableType().getQualifier().makeSpecConstant();
5130 if (qualifier.hasSpecConstantId())
5131 symbol->getWritableType().getQualifier().layoutSpecConstantId = qualifier.layoutSpecConstantId;
John Kesseniche01a9bc2016-03-12 20:11:22 -07005132 } else
5133 warn(loc, "unknown requalification", "", "");
5134}
5135
5136void HlslParseContext::addQualifierToExisting(const TSourceLoc& loc, TQualifier qualifier, TIdentifierList& identifiers)
5137{
5138 for (unsigned int i = 0; i < identifiers.size(); ++i)
5139 addQualifierToExisting(loc, qualifier, *identifiers[i]);
5140}
5141
5142//
5143// Updating default qualifier for the case of a declaration with just a qualifier,
5144// no type, block, or identifier.
5145//
5146void HlslParseContext::updateStandaloneQualifierDefaults(const TSourceLoc& loc, const TPublicType& publicType)
5147{
5148 if (publicType.shaderQualifiers.vertices != TQualifier::layoutNotSet) {
5149 assert(language == EShLangTessControl || language == EShLangGeometry);
John Kessenich7f349c72016-07-08 22:09:10 -06005150 // const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
John Kesseniche01a9bc2016-03-12 20:11:22 -07005151 }
5152 if (publicType.shaderQualifiers.invocations != TQualifier::layoutNotSet) {
5153 if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
5154 error(loc, "cannot change previously set layout value", "invocations", "");
5155 }
5156 if (publicType.shaderQualifiers.geometry != ElgNone) {
5157 if (publicType.qualifier.storage == EvqVaryingIn) {
5158 switch (publicType.shaderQualifiers.geometry) {
5159 case ElgPoints:
5160 case ElgLines:
5161 case ElgLinesAdjacency:
5162 case ElgTriangles:
5163 case ElgTrianglesAdjacency:
5164 case ElgQuads:
5165 case ElgIsolines:
John Kesseniche01a9bc2016-03-12 20:11:22 -07005166 break;
5167 default:
5168 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
5169 }
5170 } else if (publicType.qualifier.storage == EvqVaryingOut) {
5171 switch (publicType.shaderQualifiers.geometry) {
5172 case ElgPoints:
5173 case ElgLineStrip:
5174 case ElgTriangleStrip:
5175 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
5176 error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
5177 break;
5178 default:
5179 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
5180 }
5181 } else
5182 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
5183 }
5184 if (publicType.shaderQualifiers.spacing != EvsNone)
5185 intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing);
5186 if (publicType.shaderQualifiers.order != EvoNone)
5187 intermediate.setVertexOrder(publicType.shaderQualifiers.order);
5188 if (publicType.shaderQualifiers.pointMode)
5189 intermediate.setPointMode();
5190 for (int i = 0; i < 3; ++i) {
5191 if (publicType.shaderQualifiers.localSize[i] > 1) {
5192 int max = 0;
5193 switch (i) {
5194 case 0: max = resources.maxComputeWorkGroupSizeX; break;
5195 case 1: max = resources.maxComputeWorkGroupSizeY; break;
5196 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
5197 default: break;
5198 }
5199 if (intermediate.getLocalSize(i) > (unsigned int)max)
5200 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
5201
5202 // Fix the existing constant gl_WorkGroupSize with this new information.
5203 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
5204 workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
5205 }
5206 if (publicType.shaderQualifiers.localSizeSpecId[i] != TQualifier::layoutNotSet) {
5207 intermediate.setLocalSizeSpecId(i, publicType.shaderQualifiers.localSizeSpecId[i]);
5208 // Set the workgroup built-in variable as a specialization constant
5209 TVariable* workGroupSize = getEditableVariable("gl_WorkGroupSize");
5210 workGroupSize->getWritableType().getQualifier().specConstant = true;
5211 }
5212 }
5213 if (publicType.shaderQualifiers.earlyFragmentTests)
5214 intermediate.setEarlyFragmentTests();
5215
5216 const TQualifier& qualifier = publicType.qualifier;
5217
5218 switch (qualifier.storage) {
5219 case EvqUniform:
5220 if (qualifier.hasMatrix())
5221 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
5222 if (qualifier.hasPacking())
5223 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
5224 break;
5225 case EvqBuffer:
5226 if (qualifier.hasMatrix())
5227 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
5228 if (qualifier.hasPacking())
5229 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
5230 break;
5231 case EvqVaryingIn:
5232 break;
5233 case EvqVaryingOut:
5234 if (qualifier.hasStream())
5235 globalOutputDefaults.layoutStream = qualifier.layoutStream;
5236 if (qualifier.hasXfbBuffer())
5237 globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
5238 if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
5239 if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
5240 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
5241 }
5242 break;
5243 default:
5244 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
5245 return;
5246 }
5247}
5248
5249//
5250// Take the sequence of statements that has been built up since the last case/default,
5251// put it on the list of top-level nodes for the current (inner-most) switch statement,
5252// and follow that by the case/default we are on now. (See switch topology comment on
5253// TIntermSwitch.)
5254//
5255void HlslParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
5256{
5257 TIntermSequence* switchSequence = switchSequenceStack.back();
5258
5259 if (statements) {
John Kesseniche01a9bc2016-03-12 20:11:22 -07005260 statements->setOperator(EOpSequence);
5261 switchSequence->push_back(statements);
5262 }
5263 if (branchNode) {
5264 // check all previous cases for the same label (or both are 'default')
5265 for (unsigned int s = 0; s < switchSequence->size(); ++s) {
5266 TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
5267 if (prevBranch) {
5268 TIntermTyped* prevExpression = prevBranch->getExpression();
5269 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
5270 if (prevExpression == nullptr && newExpression == nullptr)
5271 error(branchNode->getLoc(), "duplicate label", "default", "");
5272 else if (prevExpression != nullptr &&
5273 newExpression != nullptr &&
5274 prevExpression->getAsConstantUnion() &&
5275 newExpression->getAsConstantUnion() &&
5276 prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
5277 newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
5278 error(branchNode->getLoc(), "duplicated value", "case", "");
5279 }
5280 }
5281 switchSequence->push_back(branchNode);
5282 }
5283}
5284
5285//
5286// Turn the top-level node sequence built up of wrapupSwitchSubsequence
5287// into a switch node.
5288//
5289TIntermNode* HlslParseContext::addSwitch(const TSourceLoc& loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
5290{
5291 wrapupSwitchSubsequence(lastStatements, nullptr);
5292
5293 if (expression == nullptr ||
5294 (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
5295 expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
5296 error(loc, "condition must be a scalar integer expression", "switch", "");
5297
5298 // If there is nothing to do, drop the switch but still execute the expression
5299 TIntermSequence* switchSequence = switchSequenceStack.back();
5300 if (switchSequence->size() == 0)
5301 return expression;
5302
5303 if (lastStatements == nullptr) {
5304 // emulate a break for error recovery
5305 lastStatements = intermediate.makeAggregate(intermediate.addBranch(EOpBreak, loc));
5306 lastStatements->setOperator(EOpSequence);
5307 switchSequence->push_back(lastStatements);
5308 }
5309
5310 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
5311 body->getSequence() = *switchSequenceStack.back();
5312 body->setLoc(loc);
5313
5314 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
5315 switchNode->setLoc(loc);
5316
5317 return switchNode;
5318}
5319
5320} // end namespace glslang