• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2014 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // ProgramD3D.cpp: Defines the rx::ProgramD3D class which implements rx::ProgramImpl.
8 
9 #include "libANGLE/renderer/d3d/ProgramD3D.h"
10 
11 #include "common/MemoryBuffer.h"
12 #include "common/bitset_utils.h"
13 #include "common/string_utils.h"
14 #include "common/utilities.h"
15 #include "libANGLE/Context.h"
16 #include "libANGLE/Framebuffer.h"
17 #include "libANGLE/FramebufferAttachment.h"
18 #include "libANGLE/Program.h"
19 #include "libANGLE/ProgramLinkedResources.h"
20 #include "libANGLE/Uniform.h"
21 #include "libANGLE/VertexArray.h"
22 #include "libANGLE/features.h"
23 #include "libANGLE/queryconversions.h"
24 #include "libANGLE/renderer/ContextImpl.h"
25 #include "libANGLE/renderer/d3d/ContextD3D.h"
26 #include "libANGLE/renderer/d3d/DynamicHLSL.h"
27 #include "libANGLE/renderer/d3d/FramebufferD3D.h"
28 #include "libANGLE/renderer/d3d/ShaderD3D.h"
29 #include "libANGLE/renderer/d3d/ShaderExecutableD3D.h"
30 #include "libANGLE/renderer/d3d/VertexDataManager.h"
31 #include "libANGLE/renderer/renderer_utils.h"
32 #include "libANGLE/trace.h"
33 
34 using namespace angle;
35 
36 namespace rx
37 {
38 
39 namespace
40 {
41 
GetDefaultInputLayoutFromShader(gl::Shader * vertexShader,gl::InputLayout * inputLayoutOut)42 void GetDefaultInputLayoutFromShader(gl::Shader *vertexShader, gl::InputLayout *inputLayoutOut)
43 {
44     inputLayoutOut->clear();
45 
46     if (!vertexShader)
47     {
48         return;
49     }
50 
51     for (const sh::ShaderVariable &shaderAttr : vertexShader->getActiveAttributes())
52     {
53         if (shaderAttr.type != GL_NONE)
54         {
55             GLenum transposedType = gl::TransposeMatrixType(shaderAttr.type);
56 
57             for (size_t rowIndex = 0;
58                  static_cast<int>(rowIndex) < gl::VariableRowCount(transposedType); ++rowIndex)
59             {
60                 GLenum componentType = gl::VariableComponentType(transposedType);
61                 GLuint components    = static_cast<GLuint>(gl::VariableColumnCount(transposedType));
62                 bool pureInt         = (componentType != GL_FLOAT);
63 
64                 gl::VertexAttribType attribType =
65                     gl::FromGLenum<gl::VertexAttribType>(componentType);
66 
67                 angle::FormatID defaultID =
68                     gl::GetVertexFormatID(attribType, GL_FALSE, components, pureInt);
69 
70                 inputLayoutOut->push_back(defaultID);
71             }
72         }
73     }
74 }
75 
GetMaxOutputIndex(const std::vector<PixelShaderOutputVariable> & shaderOutputVars,size_t location)76 size_t GetMaxOutputIndex(const std::vector<PixelShaderOutputVariable> &shaderOutputVars,
77                          size_t location)
78 {
79     size_t maxIndex = 0;
80     for (auto &outputVar : shaderOutputVars)
81     {
82         if (outputVar.outputLocation == location)
83         {
84             maxIndex = std::max(maxIndex, outputVar.outputIndex);
85         }
86     }
87     return maxIndex;
88 }
89 
GetDefaultOutputLayoutFromShader(const std::vector<PixelShaderOutputVariable> & shaderOutputVars,std::vector<GLenum> * outputLayoutOut)90 void GetDefaultOutputLayoutFromShader(
91     const std::vector<PixelShaderOutputVariable> &shaderOutputVars,
92     std::vector<GLenum> *outputLayoutOut)
93 {
94     outputLayoutOut->clear();
95 
96     if (!shaderOutputVars.empty())
97     {
98         size_t location = shaderOutputVars[0].outputLocation;
99         size_t maxIndex = GetMaxOutputIndex(shaderOutputVars, location);
100         outputLayoutOut->assign(maxIndex + 1,
101                                 GL_COLOR_ATTACHMENT0 + static_cast<unsigned int>(location));
102     }
103 }
104 
GetDefaultImage2DBindLayoutFromComputeShader(const std::vector<sh::ShaderVariable> & image2DUniforms,gl::ImageUnitTextureTypeMap * image2DBindLayout)105 void GetDefaultImage2DBindLayoutFromComputeShader(
106     const std::vector<sh::ShaderVariable> &image2DUniforms,
107     gl::ImageUnitTextureTypeMap *image2DBindLayout)
108 {
109     image2DBindLayout->clear();
110 
111     for (const sh::ShaderVariable &image2D : image2DUniforms)
112     {
113         if (gl::IsImage2DType(image2D.type))
114         {
115             if (image2D.binding == -1)
116             {
117                 image2DBindLayout->insert(std::make_pair(0, gl::TextureType::_2D));
118             }
119             else
120             {
121                 for (unsigned int index = 0; index < image2D.getArraySizeProduct(); index++)
122                 {
123                     image2DBindLayout->insert(
124                         std::make_pair(image2D.binding + index, gl::TextureType::_2D));
125                 }
126             }
127         }
128     }
129 }
130 
GetGeometryShaderTypeFromDrawMode(gl::PrimitiveMode drawMode)131 gl::PrimitiveMode GetGeometryShaderTypeFromDrawMode(gl::PrimitiveMode drawMode)
132 {
133     switch (drawMode)
134     {
135         // Uses the point sprite geometry shader.
136         case gl::PrimitiveMode::Points:
137             return gl::PrimitiveMode::Points;
138 
139         // All line drawing uses the same geometry shader.
140         case gl::PrimitiveMode::Lines:
141         case gl::PrimitiveMode::LineStrip:
142         case gl::PrimitiveMode::LineLoop:
143             return gl::PrimitiveMode::Lines;
144 
145         // The triangle fan primitive is emulated with strips in D3D11.
146         case gl::PrimitiveMode::Triangles:
147         case gl::PrimitiveMode::TriangleFan:
148             return gl::PrimitiveMode::Triangles;
149 
150         // Special case for triangle strips.
151         case gl::PrimitiveMode::TriangleStrip:
152             return gl::PrimitiveMode::TriangleStrip;
153 
154         default:
155             UNREACHABLE();
156             return gl::PrimitiveMode::InvalidEnum;
157     }
158 }
159 
HasFlatInterpolationVarying(const std::vector<sh::ShaderVariable> & varyings)160 bool HasFlatInterpolationVarying(const std::vector<sh::ShaderVariable> &varyings)
161 {
162     // Note: this assumes nested structs can only be packed with one interpolation.
163     for (const auto &varying : varyings)
164     {
165         if (varying.interpolation == sh::INTERPOLATION_FLAT)
166         {
167             return true;
168         }
169     }
170 
171     return false;
172 }
173 
FindFlatInterpolationVaryingPerShader(gl::Shader * shader)174 bool FindFlatInterpolationVaryingPerShader(gl::Shader *shader)
175 {
176     ASSERT(shader);
177     switch (shader->getType())
178     {
179         case gl::ShaderType::Vertex:
180             return HasFlatInterpolationVarying(shader->getOutputVaryings());
181         case gl::ShaderType::Fragment:
182             return HasFlatInterpolationVarying(shader->getInputVaryings());
183         case gl::ShaderType::Geometry:
184             return HasFlatInterpolationVarying(shader->getInputVaryings()) ||
185                    HasFlatInterpolationVarying(shader->getOutputVaryings());
186         default:
187             UNREACHABLE();
188             return false;
189     }
190 }
191 
FindFlatInterpolationVarying(const gl::ShaderMap<gl::Shader * > & shaders)192 bool FindFlatInterpolationVarying(const gl::ShaderMap<gl::Shader *> &shaders)
193 {
194     for (gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
195     {
196         gl::Shader *shader = shaders[shaderType];
197         if (!shader)
198         {
199             continue;
200         }
201 
202         if (FindFlatInterpolationVaryingPerShader(shader))
203         {
204             return true;
205         }
206     }
207 
208     return false;
209 }
210 
211 // Helper class that gathers uniform info from the default uniform block.
212 class UniformEncodingVisitorD3D : public sh::BlockEncoderVisitor
213 {
214   public:
UniformEncodingVisitorD3D(gl::ShaderType shaderType,HLSLRegisterType registerType,sh::BlockLayoutEncoder * encoder,D3DUniformMap * uniformMapOut)215     UniformEncodingVisitorD3D(gl::ShaderType shaderType,
216                               HLSLRegisterType registerType,
217                               sh::BlockLayoutEncoder *encoder,
218                               D3DUniformMap *uniformMapOut)
219         : sh::BlockEncoderVisitor("", "", encoder),
220           mShaderType(shaderType),
221           mRegisterType(registerType),
222           mUniformMapOut(uniformMapOut)
223     {}
224 
visitNamedOpaqueObject(const sh::ShaderVariable & sampler,const std::string & name,const std::string & mappedName,const std::vector<unsigned int> & arraySizes)225     void visitNamedOpaqueObject(const sh::ShaderVariable &sampler,
226                                 const std::string &name,
227                                 const std::string &mappedName,
228                                 const std::vector<unsigned int> &arraySizes) override
229     {
230         auto uniformMapEntry = mUniformMapOut->find(name);
231         if (uniformMapEntry == mUniformMapOut->end())
232         {
233             (*mUniformMapOut)[name] =
234                 new D3DUniform(sampler.type, mRegisterType, name, sampler.arraySizes, true);
235         }
236     }
237 
encodeVariable(const sh::ShaderVariable & variable,const sh::BlockMemberInfo & variableInfo,const std::string & name,const std::string & mappedName)238     void encodeVariable(const sh::ShaderVariable &variable,
239                         const sh::BlockMemberInfo &variableInfo,
240                         const std::string &name,
241                         const std::string &mappedName) override
242     {
243         auto uniformMapEntry   = mUniformMapOut->find(name);
244         D3DUniform *d3dUniform = nullptr;
245 
246         if (uniformMapEntry != mUniformMapOut->end())
247         {
248             d3dUniform = uniformMapEntry->second;
249         }
250         else
251         {
252             d3dUniform =
253                 new D3DUniform(variable.type, mRegisterType, name, variable.arraySizes, true);
254             (*mUniformMapOut)[name] = d3dUniform;
255         }
256 
257         d3dUniform->registerElement = static_cast<unsigned int>(
258             sh::BlockLayoutEncoder::GetBlockRegisterElement(variableInfo));
259         unsigned int reg =
260             static_cast<unsigned int>(sh::BlockLayoutEncoder::GetBlockRegister(variableInfo));
261 
262         ASSERT(mShaderType != gl::ShaderType::InvalidEnum);
263         d3dUniform->mShaderRegisterIndexes[mShaderType] = reg;
264     }
265 
266   private:
267     gl::ShaderType mShaderType;
268     HLSLRegisterType mRegisterType;
269     D3DUniformMap *mUniformMapOut;
270 };
271 
272 class HLSLBlockLayoutEncoderFactory : public gl::CustomBlockLayoutEncoderFactory
273 {
274   public:
makeEncoder()275     sh::BlockLayoutEncoder *makeEncoder() override
276     {
277         return new sh::HLSLBlockEncoder(sh::HLSLBlockEncoder::ENCODE_PACKED, false);
278     }
279 };
280 }  // anonymous namespace
281 
282 // D3DUniform Implementation
283 
D3DUniform(GLenum type,HLSLRegisterType reg,const std::string & nameIn,const std::vector<unsigned int> & arraySizesIn,bool defaultBlock)284 D3DUniform::D3DUniform(GLenum type,
285                        HLSLRegisterType reg,
286                        const std::string &nameIn,
287                        const std::vector<unsigned int> &arraySizesIn,
288                        bool defaultBlock)
289     : typeInfo(gl::GetUniformTypeInfo(type)),
290       name(nameIn),
291       arraySizes(arraySizesIn),
292       mShaderData({}),
293       regType(reg),
294       registerCount(0),
295       registerElement(0)
296 {
297     mShaderRegisterIndexes.fill(GL_INVALID_INDEX);
298 
299     // We use data storage for default block uniforms to cache values that are sent to D3D during
300     // rendering
301     // Uniform blocks/buffers are treated separately by the Renderer (ES3 path only)
302     if (defaultBlock)
303     {
304         // Use the row count as register count, will work for non-square matrices.
305         registerCount = typeInfo.rowCount * getArraySizeProduct();
306     }
307 }
308 
~D3DUniform()309 D3DUniform::~D3DUniform() {}
310 
getArraySizeProduct() const311 unsigned int D3DUniform::getArraySizeProduct() const
312 {
313     return gl::ArraySizeProduct(arraySizes);
314 }
315 
getDataPtrToElement(size_t elementIndex) const316 const uint8_t *D3DUniform::getDataPtrToElement(size_t elementIndex) const
317 {
318     ASSERT((!isArray() && elementIndex == 0) ||
319            (isArray() && elementIndex < getArraySizeProduct()));
320 
321     if (isSampler())
322     {
323         return reinterpret_cast<const uint8_t *>(&mSamplerData[elementIndex]);
324     }
325 
326     return firstNonNullData() + (elementIndex > 0 ? (typeInfo.internalSize * elementIndex) : 0u);
327 }
328 
isSampler() const329 bool D3DUniform::isSampler() const
330 {
331     return typeInfo.isSampler;
332 }
333 
isImage() const334 bool D3DUniform::isImage() const
335 {
336     return typeInfo.isImageType;
337 }
338 
isImage2D() const339 bool D3DUniform::isImage2D() const
340 {
341     return gl::IsImage2DType(typeInfo.type);
342 }
343 
isReferencedByShader(gl::ShaderType shaderType) const344 bool D3DUniform::isReferencedByShader(gl::ShaderType shaderType) const
345 {
346     return mShaderRegisterIndexes[shaderType] != GL_INVALID_INDEX;
347 }
348 
firstNonNullData() const349 const uint8_t *D3DUniform::firstNonNullData() const
350 {
351     if (!mSamplerData.empty())
352     {
353         return reinterpret_cast<const uint8_t *>(mSamplerData.data());
354     }
355 
356     for (gl::ShaderType shaderType : gl::AllShaderTypes())
357     {
358         if (mShaderData[shaderType])
359         {
360             return mShaderData[shaderType];
361         }
362     }
363 
364     UNREACHABLE();
365     return nullptr;
366 }
367 
368 // D3DInterfaceBlock Implementation
D3DInterfaceBlock()369 D3DInterfaceBlock::D3DInterfaceBlock()
370 {
371     mShaderRegisterIndexes.fill(GL_INVALID_INDEX);
372 }
373 
374 D3DInterfaceBlock::D3DInterfaceBlock(const D3DInterfaceBlock &other) = default;
375 
D3DUniformBlock()376 D3DUniformBlock::D3DUniformBlock()
377 {
378     mUseStructuredBuffers.fill(false);
379     mByteWidths.fill(0u);
380     mStructureByteStrides.fill(0u);
381 }
382 
383 D3DUniformBlock::D3DUniformBlock(const D3DUniformBlock &other) = default;
384 
385 // D3DVarying Implementation
386 
D3DVarying()387 D3DVarying::D3DVarying() : semanticIndex(0), componentCount(0), outputSlot(0) {}
388 
D3DVarying(const std::string & semanticNameIn,unsigned int semanticIndexIn,unsigned int componentCountIn,unsigned int outputSlotIn)389 D3DVarying::D3DVarying(const std::string &semanticNameIn,
390                        unsigned int semanticIndexIn,
391                        unsigned int componentCountIn,
392                        unsigned int outputSlotIn)
393     : semanticName(semanticNameIn),
394       semanticIndex(semanticIndexIn),
395       componentCount(componentCountIn),
396       outputSlot(outputSlotIn)
397 {}
398 
399 // ProgramD3DMetadata Implementation
400 
ProgramD3DMetadata(RendererD3D * renderer,const gl::ShaderMap<const ShaderD3D * > & attachedShaders,EGLenum clientType)401 ProgramD3DMetadata::ProgramD3DMetadata(RendererD3D *renderer,
402                                        const gl::ShaderMap<const ShaderD3D *> &attachedShaders,
403                                        EGLenum clientType)
404     : mRendererMajorShaderModel(renderer->getMajorShaderModel()),
405       mShaderModelSuffix(renderer->getShaderModelSuffix()),
406       mUsesInstancedPointSpriteEmulation(
407           renderer->getFeatures().useInstancedPointSpriteEmulation.enabled),
408       mUsesViewScale(renderer->presentPathFastEnabled()),
409       mCanSelectViewInVertexShader(renderer->canSelectViewInVertexShader()),
410       mAttachedShaders(attachedShaders),
411       mClientType(clientType)
412 {}
413 
414 ProgramD3DMetadata::~ProgramD3DMetadata() = default;
415 
getRendererMajorShaderModel() const416 int ProgramD3DMetadata::getRendererMajorShaderModel() const
417 {
418     return mRendererMajorShaderModel;
419 }
420 
usesBroadcast(const gl::State & data) const421 bool ProgramD3DMetadata::usesBroadcast(const gl::State &data) const
422 {
423     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
424     return (shader && shader->usesFragColor() && shader->usesMultipleRenderTargets() &&
425             data.getClientMajorVersion() < 3);
426 }
427 
usesSecondaryColor() const428 bool ProgramD3DMetadata::usesSecondaryColor() const
429 {
430     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
431     return (shader && shader->usesSecondaryColor());
432 }
433 
usesFragDepth() const434 bool ProgramD3DMetadata::usesFragDepth() const
435 {
436     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
437     return (shader && shader->usesFragDepth());
438 }
439 
usesPointCoord() const440 bool ProgramD3DMetadata::usesPointCoord() const
441 {
442     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
443     return (shader && shader->usesPointCoord());
444 }
445 
usesFragCoord() const446 bool ProgramD3DMetadata::usesFragCoord() const
447 {
448     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
449     return (shader && shader->usesFragCoord());
450 }
451 
usesPointSize() const452 bool ProgramD3DMetadata::usesPointSize() const
453 {
454     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Vertex];
455     return (shader && shader->usesPointSize());
456 }
457 
usesInsertedPointCoordValue() const458 bool ProgramD3DMetadata::usesInsertedPointCoordValue() const
459 {
460     return (!usesPointSize() || !mUsesInstancedPointSpriteEmulation) && usesPointCoord() &&
461            mRendererMajorShaderModel >= 4;
462 }
463 
usesViewScale() const464 bool ProgramD3DMetadata::usesViewScale() const
465 {
466     return mUsesViewScale;
467 }
468 
hasANGLEMultiviewEnabled() const469 bool ProgramD3DMetadata::hasANGLEMultiviewEnabled() const
470 {
471     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Vertex];
472     return (shader && shader->hasANGLEMultiviewEnabled());
473 }
474 
usesVertexID() const475 bool ProgramD3DMetadata::usesVertexID() const
476 {
477     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Vertex];
478     return (shader && shader->usesVertexID());
479 }
480 
usesViewID() const481 bool ProgramD3DMetadata::usesViewID() const
482 {
483     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
484     return (shader && shader->usesViewID());
485 }
486 
canSelectViewInVertexShader() const487 bool ProgramD3DMetadata::canSelectViewInVertexShader() const
488 {
489     return mCanSelectViewInVertexShader;
490 }
491 
addsPointCoordToVertexShader() const492 bool ProgramD3DMetadata::addsPointCoordToVertexShader() const
493 {
494     // PointSprite emulation requiress that gl_PointCoord is present in the vertex shader
495     // VS_OUTPUT structure to ensure compatibility with the generated PS_INPUT of the pixel shader.
496     // Even with a geometry shader, the app can render triangles or lines and reference
497     // gl_PointCoord in the fragment shader, requiring us to provide a placeholder value. For
498     // simplicity, we always add this to the vertex shader when the fragment shader
499     // references gl_PointCoord, even if we could skip it in the geometry shader.
500     return (mUsesInstancedPointSpriteEmulation && usesPointCoord()) ||
501            usesInsertedPointCoordValue();
502 }
503 
usesTransformFeedbackGLPosition() const504 bool ProgramD3DMetadata::usesTransformFeedbackGLPosition() const
505 {
506     // gl_Position only needs to be outputted from the vertex shader if transform feedback is
507     // active. This isn't supported on D3D11 Feature Level 9_3, so we don't output gl_Position from
508     // the vertex shader in this case. This saves us 1 output vector.
509     return !(mRendererMajorShaderModel >= 4 && mShaderModelSuffix != "");
510 }
511 
usesSystemValuePointSize() const512 bool ProgramD3DMetadata::usesSystemValuePointSize() const
513 {
514     return !mUsesInstancedPointSpriteEmulation && usesPointSize();
515 }
516 
usesMultipleFragmentOuts() const517 bool ProgramD3DMetadata::usesMultipleFragmentOuts() const
518 {
519     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Fragment];
520     return (shader && shader->usesMultipleRenderTargets());
521 }
522 
usesCustomOutVars() const523 bool ProgramD3DMetadata::usesCustomOutVars() const
524 {
525 
526     const rx::ShaderD3D *shader = mAttachedShaders[gl::ShaderType::Vertex];
527     int version                 = shader ? shader->getState().getShaderVersion() : -1;
528 
529     switch (mClientType)
530     {
531         case EGL_OPENGL_API:
532             return version >= 130;
533         default:
534             return version >= 300;
535     }
536 }
537 
getFragmentShader() const538 const ShaderD3D *ProgramD3DMetadata::getFragmentShader() const
539 {
540     return mAttachedShaders[gl::ShaderType::Fragment];
541 }
542 
543 // ProgramD3D::GetExecutableTask class
544 class ProgramD3D::GetExecutableTask : public Closure, public d3d::Context
545 {
546   public:
GetExecutableTask(ProgramD3D * program)547     GetExecutableTask(ProgramD3D *program) : mProgram(program) {}
548 
549     virtual angle::Result run() = 0;
550 
operator ()()551     void operator()() override { mResult = run(); }
552 
getResult() const553     angle::Result getResult() const { return mResult; }
getInfoLog() const554     const gl::InfoLog &getInfoLog() const { return mInfoLog; }
getExecutable()555     ShaderExecutableD3D *getExecutable() { return mExecutable; }
556 
handleResult(HRESULT hr,const char * message,const char * file,const char * function,unsigned int line)557     void handleResult(HRESULT hr,
558                       const char *message,
559                       const char *file,
560                       const char *function,
561                       unsigned int line) override
562     {
563         mStoredHR       = hr;
564         mStoredMessage  = message;
565         mStoredFile     = file;
566         mStoredFunction = function;
567         mStoredLine     = line;
568     }
569 
popError(d3d::Context * context)570     void popError(d3d::Context *context)
571     {
572         ASSERT(mStoredFile);
573         ASSERT(mStoredFunction);
574         context->handleResult(mStoredHR, mStoredMessage.c_str(), mStoredFile, mStoredFunction,
575                               mStoredLine);
576     }
577 
578   protected:
579     ProgramD3D *mProgram  = nullptr;
580     angle::Result mResult = angle::Result::Continue;
581     gl::InfoLog mInfoLog;
582     ShaderExecutableD3D *mExecutable = nullptr;
583     HRESULT mStoredHR                = S_OK;
584     std::string mStoredMessage;
585     const char *mStoredFile     = nullptr;
586     const char *mStoredFunction = nullptr;
587     unsigned int mStoredLine    = 0;
588 };
589 
590 // ProgramD3D Implementation
591 
VertexExecutable(const gl::InputLayout & inputLayout,const Signature & signature,ShaderExecutableD3D * shaderExecutable)592 ProgramD3D::VertexExecutable::VertexExecutable(const gl::InputLayout &inputLayout,
593                                                const Signature &signature,
594                                                ShaderExecutableD3D *shaderExecutable)
595     : mInputs(inputLayout), mSignature(signature), mShaderExecutable(shaderExecutable)
596 {}
597 
~VertexExecutable()598 ProgramD3D::VertexExecutable::~VertexExecutable()
599 {
600     SafeDelete(mShaderExecutable);
601 }
602 
603 // static
GetAttribType(GLenum type)604 ProgramD3D::VertexExecutable::HLSLAttribType ProgramD3D::VertexExecutable::GetAttribType(
605     GLenum type)
606 {
607     switch (type)
608     {
609         case GL_INT:
610             return HLSLAttribType::SIGNED_INT;
611         case GL_UNSIGNED_INT:
612             return HLSLAttribType::UNSIGNED_INT;
613         case GL_SIGNED_NORMALIZED:
614         case GL_UNSIGNED_NORMALIZED:
615         case GL_FLOAT:
616             return HLSLAttribType::FLOAT;
617         default:
618             UNREACHABLE();
619             return HLSLAttribType::FLOAT;
620     }
621 }
622 
623 // static
getSignature(RendererD3D * renderer,const gl::InputLayout & inputLayout,Signature * signatureOut)624 void ProgramD3D::VertexExecutable::getSignature(RendererD3D *renderer,
625                                                 const gl::InputLayout &inputLayout,
626                                                 Signature *signatureOut)
627 {
628     signatureOut->assign(inputLayout.size(), HLSLAttribType::FLOAT);
629 
630     for (size_t index = 0; index < inputLayout.size(); ++index)
631     {
632         angle::FormatID vertexFormatID = inputLayout[index];
633         if (vertexFormatID == angle::FormatID::NONE)
634             continue;
635 
636         VertexConversionType conversionType = renderer->getVertexConversionType(vertexFormatID);
637         if ((conversionType & VERTEX_CONVERT_GPU) == 0)
638             continue;
639 
640         GLenum componentType   = renderer->getVertexComponentType(vertexFormatID);
641         (*signatureOut)[index] = GetAttribType(componentType);
642     }
643 }
644 
matchesSignature(const Signature & signature) const645 bool ProgramD3D::VertexExecutable::matchesSignature(const Signature &signature) const
646 {
647     size_t limit = std::max(mSignature.size(), signature.size());
648     for (size_t index = 0; index < limit; ++index)
649     {
650         // treat undefined indexes as FLOAT
651         auto a = index < signature.size() ? signature[index] : HLSLAttribType::FLOAT;
652         auto b = index < mSignature.size() ? mSignature[index] : HLSLAttribType::FLOAT;
653         if (a != b)
654             return false;
655     }
656 
657     return true;
658 }
659 
PixelExecutable(const std::vector<GLenum> & outputSignature,ShaderExecutableD3D * shaderExecutable)660 ProgramD3D::PixelExecutable::PixelExecutable(const std::vector<GLenum> &outputSignature,
661                                              ShaderExecutableD3D *shaderExecutable)
662     : mOutputSignature(outputSignature), mShaderExecutable(shaderExecutable)
663 {}
664 
~PixelExecutable()665 ProgramD3D::PixelExecutable::~PixelExecutable()
666 {
667     SafeDelete(mShaderExecutable);
668 }
669 
ComputeExecutable(const gl::ImageUnitTextureTypeMap & signature,std::unique_ptr<ShaderExecutableD3D> shaderExecutable)670 ProgramD3D::ComputeExecutable::ComputeExecutable(
671     const gl::ImageUnitTextureTypeMap &signature,
672     std::unique_ptr<ShaderExecutableD3D> shaderExecutable)
673     : mSignature(signature), mShaderExecutable(std::move(shaderExecutable))
674 {}
675 
~ComputeExecutable()676 ProgramD3D::ComputeExecutable::~ComputeExecutable() {}
677 
Sampler()678 ProgramD3D::Sampler::Sampler()
679     : active(false), logicalTextureUnit(0), textureType(gl::TextureType::_2D)
680 {}
681 
Image()682 ProgramD3D::Image::Image() : active(false), logicalImageUnit(0) {}
683 
684 unsigned int ProgramD3D::mCurrentSerial = 1;
685 
ProgramD3D(const gl::ProgramState & state,RendererD3D * renderer)686 ProgramD3D::ProgramD3D(const gl::ProgramState &state, RendererD3D *renderer)
687     : ProgramImpl(state),
688       mRenderer(renderer),
689       mDynamicHLSL(nullptr),
690       mUsesPointSize(false),
691       mUsesFlatInterpolation(false),
692       mUsedShaderSamplerRanges({}),
693       mDirtySamplerMapping(true),
694       mUsedComputeImageRange(0, 0),
695       mUsedComputeReadonlyImageRange(0, 0),
696       mUsedComputeAtomicCounterRange(0, 0),
697       mSerial(issueSerial())
698 {
699     mDynamicHLSL = new DynamicHLSL(renderer);
700 }
701 
~ProgramD3D()702 ProgramD3D::~ProgramD3D()
703 {
704     reset();
705     SafeDelete(mDynamicHLSL);
706 }
707 
usesPointSpriteEmulation() const708 bool ProgramD3D::usesPointSpriteEmulation() const
709 {
710     return mUsesPointSize && mRenderer->getMajorShaderModel() >= 4;
711 }
712 
usesGeometryShaderForPointSpriteEmulation() const713 bool ProgramD3D::usesGeometryShaderForPointSpriteEmulation() const
714 {
715     return usesPointSpriteEmulation() && !usesInstancedPointSpriteEmulation();
716 }
717 
usesGetDimensionsIgnoresBaseLevel() const718 bool ProgramD3D::usesGetDimensionsIgnoresBaseLevel() const
719 {
720     return mRenderer->getFeatures().getDimensionsIgnoresBaseLevel.enabled;
721 }
722 
usesGeometryShader(const gl::State & state,const gl::PrimitiveMode drawMode) const723 bool ProgramD3D::usesGeometryShader(const gl::State &state, const gl::PrimitiveMode drawMode) const
724 {
725     if (mHasANGLEMultiviewEnabled && !mRenderer->canSelectViewInVertexShader())
726     {
727         return true;
728     }
729     if (drawMode != gl::PrimitiveMode::Points)
730     {
731         if (!mUsesFlatInterpolation)
732         {
733             return false;
734         }
735         return state.getProvokingVertex() == gl::ProvokingVertexConvention::LastVertexConvention;
736     }
737     return usesGeometryShaderForPointSpriteEmulation();
738 }
739 
usesInstancedPointSpriteEmulation() const740 bool ProgramD3D::usesInstancedPointSpriteEmulation() const
741 {
742     return mRenderer->getFeatures().useInstancedPointSpriteEmulation.enabled;
743 }
744 
getSamplerMapping(gl::ShaderType type,unsigned int samplerIndex,const gl::Caps & caps) const745 GLint ProgramD3D::getSamplerMapping(gl::ShaderType type,
746                                     unsigned int samplerIndex,
747                                     const gl::Caps &caps) const
748 {
749     GLint logicalTextureUnit = -1;
750 
751     ASSERT(type != gl::ShaderType::InvalidEnum);
752 
753     ASSERT(samplerIndex < static_cast<unsigned int>(caps.maxShaderTextureImageUnits[type]));
754 
755     const auto &samplers = mShaderSamplers[type];
756     if (samplerIndex < samplers.size() && samplers[samplerIndex].active)
757     {
758         logicalTextureUnit = samplers[samplerIndex].logicalTextureUnit;
759     }
760 
761     if (logicalTextureUnit >= 0 && logicalTextureUnit < caps.maxCombinedTextureImageUnits)
762     {
763         return logicalTextureUnit;
764     }
765 
766     return -1;
767 }
768 
769 // Returns the texture type for a given Direct3D 9 sampler type and
770 // index (0-15 for the pixel shader and 0-3 for the vertex shader).
getSamplerTextureType(gl::ShaderType type,unsigned int samplerIndex) const771 gl::TextureType ProgramD3D::getSamplerTextureType(gl::ShaderType type,
772                                                   unsigned int samplerIndex) const
773 {
774     ASSERT(type != gl::ShaderType::InvalidEnum);
775 
776     const auto &samplers = mShaderSamplers[type];
777     ASSERT(samplerIndex < samplers.size());
778     ASSERT(samplers[samplerIndex].active);
779 
780     return samplers[samplerIndex].textureType;
781 }
782 
getUsedSamplerRange(gl::ShaderType type) const783 gl::RangeUI ProgramD3D::getUsedSamplerRange(gl::ShaderType type) const
784 {
785     ASSERT(type != gl::ShaderType::InvalidEnum);
786     return mUsedShaderSamplerRanges[type];
787 }
788 
updateSamplerMapping()789 ProgramD3D::SamplerMapping ProgramD3D::updateSamplerMapping()
790 {
791     if (!mDirtySamplerMapping)
792     {
793         return SamplerMapping::WasClean;
794     }
795 
796     mDirtySamplerMapping = false;
797 
798     // Retrieve sampler uniform values
799     for (const D3DUniform *d3dUniform : mD3DUniforms)
800     {
801         if (!d3dUniform->isSampler())
802             continue;
803 
804         int count = d3dUniform->getArraySizeProduct();
805 
806         for (gl::ShaderType shaderType : gl::AllShaderTypes())
807         {
808             if (!d3dUniform->isReferencedByShader(shaderType))
809             {
810                 continue;
811             }
812 
813             unsigned int firstIndex = d3dUniform->mShaderRegisterIndexes[shaderType];
814 
815             std::vector<Sampler> &samplers = mShaderSamplers[shaderType];
816             for (int i = 0; i < count; i++)
817             {
818                 unsigned int samplerIndex = firstIndex + i;
819 
820                 if (samplerIndex < samplers.size())
821                 {
822                     ASSERT(samplers[samplerIndex].active);
823                     samplers[samplerIndex].logicalTextureUnit = d3dUniform->mSamplerData[i];
824                 }
825             }
826         }
827     }
828 
829     return SamplerMapping::WasDirty;
830 }
831 
getImageMapping(gl::ShaderType type,unsigned int imageIndex,bool readonly,const gl::Caps & caps) const832 GLint ProgramD3D::getImageMapping(gl::ShaderType type,
833                                   unsigned int imageIndex,
834                                   bool readonly,
835                                   const gl::Caps &caps) const
836 {
837     GLint logicalImageUnit = -1;
838     ASSERT(imageIndex < static_cast<unsigned int>(caps.maxImageUnits));
839     switch (type)
840     {
841         case gl::ShaderType::Compute:
842             if (readonly && imageIndex < mReadonlyImagesCS.size() &&
843                 mReadonlyImagesCS[imageIndex].active)
844             {
845                 logicalImageUnit = mReadonlyImagesCS[imageIndex].logicalImageUnit;
846             }
847             else if (imageIndex < mImagesCS.size() && mImagesCS[imageIndex].active)
848             {
849                 logicalImageUnit = mImagesCS[imageIndex].logicalImageUnit;
850             }
851             break;
852         // TODO(xinghua.cao@intel.com): add image mapping for vertex shader and pixel shader.
853         default:
854             UNREACHABLE();
855     }
856 
857     if (logicalImageUnit >= 0 && logicalImageUnit < caps.maxImageUnits)
858     {
859         return logicalImageUnit;
860     }
861 
862     return -1;
863 }
864 
getUsedImageRange(gl::ShaderType type,bool readonly) const865 gl::RangeUI ProgramD3D::getUsedImageRange(gl::ShaderType type, bool readonly) const
866 {
867     switch (type)
868     {
869         case gl::ShaderType::Compute:
870             return readonly ? mUsedComputeReadonlyImageRange : mUsedComputeImageRange;
871         // TODO(xinghua.cao@intel.com): add real image range of vertex shader and pixel shader.
872         case gl::ShaderType::Vertex:
873         case gl::ShaderType::Fragment:
874             return {0, 0};
875         default:
876             UNREACHABLE();
877             return {0, 0};
878     }
879 }
880 
881 class ProgramD3D::LoadBinaryTask : public ProgramD3D::GetExecutableTask
882 {
883   public:
LoadBinaryTask(ProgramD3D * program,gl::BinaryInputStream * stream,gl::InfoLog & infoLog)884     LoadBinaryTask(ProgramD3D *program, gl::BinaryInputStream *stream, gl::InfoLog &infoLog)
885         : ProgramD3D::GetExecutableTask(program)
886     {
887         ASSERT(mProgram);
888         ASSERT(stream);
889 
890         // Copy the remaining data from the stream locally so that the client can't modify it when
891         // loading off thread.
892         size_t dataSize    = stream->remainingSize();
893         mDataCopySucceeded = mStreamData.resize(dataSize);
894         if (mDataCopySucceeded)
895         {
896             memcpy(mStreamData.data(), stream->data() + stream->offset(), dataSize);
897         }
898     }
899 
run()900     angle::Result run() override
901     {
902         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::LoadBinaryTask::run");
903         if (!mDataCopySucceeded)
904         {
905             mInfoLog << "Failed to copy program binary data to local buffer.";
906             return angle::Result::Incomplete;
907         }
908 
909         gl::BinaryInputStream stream(mStreamData.data(), mStreamData.size());
910         return mProgram->loadBinaryShaderExecutables(this, &stream, mInfoLog);
911     }
912 
913   private:
914     bool mDataCopySucceeded;
915     angle::MemoryBuffer mStreamData;
916 };
917 
918 class ProgramD3D::LoadBinaryLinkEvent final : public LinkEvent
919 {
920   public:
LoadBinaryLinkEvent(std::shared_ptr<WorkerThreadPool> workerPool,ProgramD3D * program,gl::BinaryInputStream * stream,gl::InfoLog & infoLog)921     LoadBinaryLinkEvent(std::shared_ptr<WorkerThreadPool> workerPool,
922                         ProgramD3D *program,
923                         gl::BinaryInputStream *stream,
924                         gl::InfoLog &infoLog)
925         : mTask(std::make_shared<ProgramD3D::LoadBinaryTask>(program, stream, infoLog)),
926           mWaitableEvent(angle::WorkerThreadPool::PostWorkerTask(workerPool, mTask))
927     {}
928 
wait(const gl::Context * context)929     angle::Result wait(const gl::Context *context) override
930     {
931         mWaitableEvent->wait();
932 
933         // Continue and Incomplete are not errors. For Stop, pass the error to the ContextD3D.
934         if (mTask->getResult() != angle::Result::Stop)
935         {
936             return angle::Result::Continue;
937         }
938 
939         ContextD3D *contextD3D = GetImplAs<ContextD3D>(context);
940         mTask->popError(contextD3D);
941         return angle::Result::Stop;
942     }
943 
isLinking()944     bool isLinking() override { return !mWaitableEvent->isReady(); }
945 
946   private:
947     std::shared_ptr<ProgramD3D::LoadBinaryTask> mTask;
948     std::shared_ptr<WaitableEvent> mWaitableEvent;
949 };
950 
load(const gl::Context * context,gl::BinaryInputStream * stream,gl::InfoLog & infoLog)951 std::unique_ptr<rx::LinkEvent> ProgramD3D::load(const gl::Context *context,
952                                                 gl::BinaryInputStream *stream,
953                                                 gl::InfoLog &infoLog)
954 {
955 
956     // TODO(jmadill): Use Renderer from contextImpl.
957 
958     reset();
959 
960     DeviceIdentifier binaryDeviceIdentifier = {};
961     stream->readBytes(reinterpret_cast<unsigned char *>(&binaryDeviceIdentifier),
962                       sizeof(DeviceIdentifier));
963 
964     DeviceIdentifier identifier = mRenderer->getAdapterIdentifier();
965     if (memcmp(&identifier, &binaryDeviceIdentifier, sizeof(DeviceIdentifier)) != 0)
966     {
967         infoLog << "Invalid program binary, device configuration has changed.";
968         return nullptr;
969     }
970 
971     int compileFlags = stream->readInt<int>();
972     if (compileFlags != ANGLE_COMPILE_OPTIMIZATION_LEVEL)
973     {
974         infoLog << "Mismatched compilation flags.";
975         return nullptr;
976     }
977 
978     for (int &index : mAttribLocationToD3DSemantic)
979     {
980         stream->readInt(&index);
981     }
982 
983     for (gl::ShaderType shaderType : gl::AllShaderTypes())
984     {
985         size_t samplerCount = stream->readInt<size_t>();
986         for (size_t sampleIndex = 0; sampleIndex < samplerCount; ++sampleIndex)
987         {
988             Sampler sampler;
989             stream->readBool(&sampler.active);
990             stream->readInt(&sampler.logicalTextureUnit);
991             stream->readEnum(&sampler.textureType);
992             mShaderSamplers[shaderType].push_back(sampler);
993         }
994 
995         unsigned int samplerRangeLow, samplerRangeHigh;
996         stream->readInt(&samplerRangeLow);
997         stream->readInt(&samplerRangeHigh);
998         mUsedShaderSamplerRanges[shaderType] = gl::RangeUI(samplerRangeLow, samplerRangeHigh);
999     }
1000 
1001     size_t csImageCount = stream->readInt<size_t>();
1002     for (size_t imageIndex = 0; imageIndex < csImageCount; ++imageIndex)
1003     {
1004         Image image;
1005         stream->readBool(&image.active);
1006         stream->readInt(&image.logicalImageUnit);
1007         mImagesCS.push_back(image);
1008     }
1009 
1010     size_t csReadonlyImageCount = stream->readInt<size_t>();
1011     for (size_t imageIndex = 0; imageIndex < csReadonlyImageCount; ++imageIndex)
1012     {
1013         Image image;
1014         stream->readBool(&image.active);
1015         stream->readInt(&image.logicalImageUnit);
1016         mReadonlyImagesCS.push_back(image);
1017     }
1018 
1019     unsigned int computeImageRangeLow, computeImageRangeHigh, computeReadonlyImageRangeLow,
1020         computeReadonlyImageRangeHigh;
1021     stream->readInt(&computeImageRangeLow);
1022     stream->readInt(&computeImageRangeHigh);
1023     stream->readInt(&computeReadonlyImageRangeLow);
1024     stream->readInt(&computeReadonlyImageRangeHigh);
1025     mUsedComputeImageRange = gl::RangeUI(computeImageRangeLow, computeImageRangeHigh);
1026     mUsedComputeReadonlyImageRange =
1027         gl::RangeUI(computeReadonlyImageRangeLow, computeReadonlyImageRangeHigh);
1028 
1029     unsigned int atomicCounterRangeLow, atomicCounterRangeHigh;
1030     stream->readInt(&atomicCounterRangeLow);
1031     stream->readInt(&atomicCounterRangeHigh);
1032     mUsedComputeAtomicCounterRange = gl::RangeUI(atomicCounterRangeLow, atomicCounterRangeHigh);
1033 
1034     size_t shaderStorageBlockCount = stream->readInt<size_t>();
1035     if (stream->error())
1036     {
1037         infoLog << "Invalid program binary.";
1038         return nullptr;
1039     }
1040 
1041     ASSERT(mD3DShaderStorageBlocks.empty());
1042     for (size_t blockIndex = 0; blockIndex < shaderStorageBlockCount; ++blockIndex)
1043     {
1044         D3DInterfaceBlock shaderStorageBlock;
1045         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1046         {
1047             stream->readInt(&shaderStorageBlock.mShaderRegisterIndexes[shaderType]);
1048         }
1049         mD3DShaderStorageBlocks.push_back(shaderStorageBlock);
1050     }
1051 
1052     size_t image2DUniformCount = stream->readInt<size_t>();
1053     if (stream->error())
1054     {
1055         infoLog << "Invalid program binary.";
1056         return nullptr;
1057     }
1058 
1059     ASSERT(mImage2DUniforms.empty());
1060     for (size_t image2DUniformIndex = 0; image2DUniformIndex < image2DUniformCount;
1061          ++image2DUniformIndex)
1062     {
1063         sh::ShaderVariable image2Duniform;
1064         gl::LoadShaderVar(stream, &image2Duniform);
1065         mImage2DUniforms.push_back(image2Duniform);
1066     }
1067 
1068     for (unsigned int ii = 0; ii < gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS; ++ii)
1069     {
1070         unsigned int index                             = stream->readInt<unsigned int>();
1071         mComputeAtomicCounterBufferRegisterIndices[ii] = index;
1072     }
1073 
1074     size_t uniformCount = stream->readInt<size_t>();
1075     if (stream->error())
1076     {
1077         infoLog << "Invalid program binary.";
1078         return nullptr;
1079     }
1080 
1081     const auto &linkedUniforms = mState.getUniforms();
1082     ASSERT(mD3DUniforms.empty());
1083     for (size_t uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++)
1084     {
1085         const gl::LinkedUniform &linkedUniform = linkedUniforms[uniformIndex];
1086 
1087         D3DUniform *d3dUniform =
1088             new D3DUniform(linkedUniform.type, HLSLRegisterType::None, linkedUniform.name,
1089                            linkedUniform.arraySizes, linkedUniform.isInDefaultBlock());
1090         stream->readEnum(&d3dUniform->regType);
1091         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1092         {
1093             stream->readInt(&d3dUniform->mShaderRegisterIndexes[shaderType]);
1094         }
1095         stream->readInt(&d3dUniform->registerCount);
1096         stream->readInt(&d3dUniform->registerElement);
1097 
1098         mD3DUniforms.push_back(d3dUniform);
1099     }
1100 
1101     size_t blockCount = stream->readInt<size_t>();
1102     if (stream->error())
1103     {
1104         infoLog << "Invalid program binary.";
1105         return nullptr;
1106     }
1107 
1108     ASSERT(mD3DUniformBlocks.empty());
1109     for (size_t blockIndex = 0; blockIndex < blockCount; ++blockIndex)
1110     {
1111         D3DUniformBlock uniformBlock;
1112         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1113         {
1114             stream->readInt(&uniformBlock.mShaderRegisterIndexes[shaderType]);
1115             stream->readBool(&uniformBlock.mUseStructuredBuffers[shaderType]);
1116             stream->readInt(&uniformBlock.mByteWidths[shaderType]);
1117             stream->readInt(&uniformBlock.mStructureByteStrides[shaderType]);
1118         }
1119         mD3DUniformBlocks.push_back(uniformBlock);
1120     }
1121 
1122     size_t streamOutVaryingCount = stream->readInt<size_t>();
1123     mStreamOutVaryings.resize(streamOutVaryingCount);
1124     for (size_t varyingIndex = 0; varyingIndex < streamOutVaryingCount; ++varyingIndex)
1125     {
1126         D3DVarying *varying = &mStreamOutVaryings[varyingIndex];
1127 
1128         stream->readString(&varying->semanticName);
1129         stream->readInt(&varying->semanticIndex);
1130         stream->readInt(&varying->componentCount);
1131         stream->readInt(&varying->outputSlot);
1132     }
1133 
1134     for (gl::ShaderType shaderType : gl::AllShaderTypes())
1135     {
1136         stream->readString(&mShaderHLSL[shaderType]);
1137         stream->readBytes(reinterpret_cast<unsigned char *>(&mShaderWorkarounds[shaderType]),
1138                           sizeof(angle::CompilerWorkaroundsD3D));
1139     }
1140 
1141     stream->readBool(&mUsesFragDepth);
1142     stream->readBool(&mHasANGLEMultiviewEnabled);
1143     stream->readBool(&mUsesVertexID);
1144     stream->readBool(&mUsesViewID);
1145     stream->readBool(&mUsesPointSize);
1146     stream->readBool(&mUsesFlatInterpolation);
1147 
1148     const size_t pixelShaderKeySize = stream->readInt<size_t>();
1149     mPixelShaderKey.resize(pixelShaderKeySize);
1150     for (size_t pixelShaderKeyIndex = 0; pixelShaderKeyIndex < pixelShaderKeySize;
1151          pixelShaderKeyIndex++)
1152     {
1153         stream->readInt(&mPixelShaderKey[pixelShaderKeyIndex].type);
1154         stream->readString(&mPixelShaderKey[pixelShaderKeyIndex].name);
1155         stream->readString(&mPixelShaderKey[pixelShaderKeyIndex].source);
1156         stream->readInt(&mPixelShaderKey[pixelShaderKeyIndex].outputLocation);
1157         stream->readInt(&mPixelShaderKey[pixelShaderKeyIndex].outputIndex);
1158     }
1159 
1160     stream->readString(&mGeometryShaderPreamble);
1161 
1162     return std::make_unique<LoadBinaryLinkEvent>(context->getWorkerThreadPool(), this, stream,
1163                                                  infoLog);
1164 }
1165 
loadBinaryShaderExecutables(d3d::Context * contextD3D,gl::BinaryInputStream * stream,gl::InfoLog & infoLog)1166 angle::Result ProgramD3D::loadBinaryShaderExecutables(d3d::Context *contextD3D,
1167                                                       gl::BinaryInputStream *stream,
1168                                                       gl::InfoLog &infoLog)
1169 {
1170     const unsigned char *binary = reinterpret_cast<const unsigned char *>(stream->data());
1171 
1172     bool separateAttribs = (mState.getTransformFeedbackBufferMode() == GL_SEPARATE_ATTRIBS);
1173 
1174     size_t vertexShaderCount = stream->readInt<size_t>();
1175     for (size_t vertexShaderIndex = 0; vertexShaderIndex < vertexShaderCount; vertexShaderIndex++)
1176     {
1177         size_t inputLayoutSize = stream->readInt<size_t>();
1178         gl::InputLayout inputLayout(inputLayoutSize, angle::FormatID::NONE);
1179 
1180         for (size_t inputIndex = 0; inputIndex < inputLayoutSize; inputIndex++)
1181         {
1182             inputLayout[inputIndex] = stream->readEnum<angle::FormatID>();
1183         }
1184 
1185         size_t vertexShaderSize                   = stream->readInt<size_t>();
1186         const unsigned char *vertexShaderFunction = binary + stream->offset();
1187 
1188         ShaderExecutableD3D *shaderExecutable = nullptr;
1189 
1190         ANGLE_TRY(mRenderer->loadExecutable(contextD3D, vertexShaderFunction, vertexShaderSize,
1191                                             gl::ShaderType::Vertex, mStreamOutVaryings,
1192                                             separateAttribs, &shaderExecutable));
1193 
1194         if (!shaderExecutable)
1195         {
1196             infoLog << "Could not create vertex shader.";
1197             return angle::Result::Incomplete;
1198         }
1199 
1200         // generated converted input layout
1201         VertexExecutable::Signature signature;
1202         VertexExecutable::getSignature(mRenderer, inputLayout, &signature);
1203 
1204         // add new binary
1205         mVertexExecutables.push_back(std::unique_ptr<VertexExecutable>(
1206             new VertexExecutable(inputLayout, signature, shaderExecutable)));
1207 
1208         stream->skip(vertexShaderSize);
1209     }
1210 
1211     size_t pixelShaderCount = stream->readInt<size_t>();
1212     for (size_t pixelShaderIndex = 0; pixelShaderIndex < pixelShaderCount; pixelShaderIndex++)
1213     {
1214         size_t outputCount = stream->readInt<size_t>();
1215         std::vector<GLenum> outputs(outputCount);
1216         for (size_t outputIndex = 0; outputIndex < outputCount; outputIndex++)
1217         {
1218             stream->readInt(&outputs[outputIndex]);
1219         }
1220 
1221         size_t pixelShaderSize                   = stream->readInt<size_t>();
1222         const unsigned char *pixelShaderFunction = binary + stream->offset();
1223         ShaderExecutableD3D *shaderExecutable    = nullptr;
1224 
1225         ANGLE_TRY(mRenderer->loadExecutable(contextD3D, pixelShaderFunction, pixelShaderSize,
1226                                             gl::ShaderType::Fragment, mStreamOutVaryings,
1227                                             separateAttribs, &shaderExecutable));
1228 
1229         if (!shaderExecutable)
1230         {
1231             infoLog << "Could not create pixel shader.";
1232             return angle::Result::Incomplete;
1233         }
1234 
1235         // add new binary
1236         mPixelExecutables.push_back(
1237             std::unique_ptr<PixelExecutable>(new PixelExecutable(outputs, shaderExecutable)));
1238 
1239         stream->skip(pixelShaderSize);
1240     }
1241 
1242     for (std::unique_ptr<ShaderExecutableD3D> &geometryExe : mGeometryExecutables)
1243     {
1244         size_t geometryShaderSize = stream->readInt<size_t>();
1245         if (geometryShaderSize == 0)
1246         {
1247             continue;
1248         }
1249 
1250         const unsigned char *geometryShaderFunction = binary + stream->offset();
1251 
1252         ShaderExecutableD3D *geometryExecutable = nullptr;
1253         ANGLE_TRY(mRenderer->loadExecutable(contextD3D, geometryShaderFunction, geometryShaderSize,
1254                                             gl::ShaderType::Geometry, mStreamOutVaryings,
1255                                             separateAttribs, &geometryExecutable));
1256 
1257         if (!geometryExecutable)
1258         {
1259             infoLog << "Could not create geometry shader.";
1260             return angle::Result::Incomplete;
1261         }
1262 
1263         geometryExe.reset(geometryExecutable);
1264 
1265         stream->skip(geometryShaderSize);
1266     }
1267 
1268     size_t computeShaderCount = stream->readInt<size_t>();
1269     for (size_t computeShaderIndex = 0; computeShaderIndex < computeShaderCount;
1270          computeShaderIndex++)
1271     {
1272         size_t signatureCount = stream->readInt<size_t>();
1273         gl::ImageUnitTextureTypeMap signatures;
1274         for (size_t signatureIndex = 0; signatureIndex < signatureCount; signatureIndex++)
1275         {
1276             unsigned int imageUint;
1277             gl::TextureType textureType;
1278             stream->readInt(&imageUint);
1279             stream->readEnum(&textureType);
1280             signatures.insert(std::pair<unsigned int, gl::TextureType>(imageUint, textureType));
1281         }
1282 
1283         size_t computeShaderSize                   = stream->readInt<size_t>();
1284         const unsigned char *computeShaderFunction = binary + stream->offset();
1285 
1286         ShaderExecutableD3D *computeExecutable = nullptr;
1287         ANGLE_TRY(mRenderer->loadExecutable(contextD3D, computeShaderFunction, computeShaderSize,
1288                                             gl::ShaderType::Compute, std::vector<D3DVarying>(),
1289                                             false, &computeExecutable));
1290 
1291         if (!computeExecutable)
1292         {
1293             infoLog << "Could not create compute shader.";
1294             return angle::Result::Incomplete;
1295         }
1296 
1297         // add new binary
1298         mComputeExecutables.push_back(std::unique_ptr<ComputeExecutable>(new ComputeExecutable(
1299             signatures, std::unique_ptr<ShaderExecutableD3D>(computeExecutable))));
1300 
1301         stream->skip(computeShaderSize);
1302     }
1303 
1304     size_t bindLayoutCount = stream->readInt<size_t>();
1305     for (size_t bindLayoutIndex = 0; bindLayoutIndex < bindLayoutCount; bindLayoutIndex++)
1306     {
1307         mComputeShaderImage2DBindLayoutCache.insert(std::pair<unsigned int, gl::TextureType>(
1308             stream->readInt<unsigned int>(), gl::TextureType::_2D));
1309     }
1310 
1311     initializeUniformStorage(mState.getExecutable().getLinkedShaderStages());
1312 
1313     dirtyAllUniforms();
1314 
1315     return angle::Result::Continue;
1316 }
1317 
save(const gl::Context * context,gl::BinaryOutputStream * stream)1318 void ProgramD3D::save(const gl::Context *context, gl::BinaryOutputStream *stream)
1319 {
1320     // Output the DeviceIdentifier before we output any shader code
1321     // When we load the binary again later, we can validate the device identifier before trying to
1322     // compile any HLSL
1323     DeviceIdentifier binaryIdentifier = mRenderer->getAdapterIdentifier();
1324     stream->writeBytes(reinterpret_cast<unsigned char *>(&binaryIdentifier),
1325                        sizeof(DeviceIdentifier));
1326 
1327     stream->writeInt(ANGLE_COMPILE_OPTIMIZATION_LEVEL);
1328 
1329     for (int d3dSemantic : mAttribLocationToD3DSemantic)
1330     {
1331         stream->writeInt(d3dSemantic);
1332     }
1333 
1334     for (gl::ShaderType shaderType : gl::AllShaderTypes())
1335     {
1336         stream->writeInt(mShaderSamplers[shaderType].size());
1337         for (unsigned int i = 0; i < mShaderSamplers[shaderType].size(); ++i)
1338         {
1339             stream->writeBool(mShaderSamplers[shaderType][i].active);
1340             stream->writeInt(mShaderSamplers[shaderType][i].logicalTextureUnit);
1341             stream->writeEnum(mShaderSamplers[shaderType][i].textureType);
1342         }
1343 
1344         stream->writeInt(mUsedShaderSamplerRanges[shaderType].low());
1345         stream->writeInt(mUsedShaderSamplerRanges[shaderType].high());
1346     }
1347 
1348     stream->writeInt(mImagesCS.size());
1349     for (size_t imageIndex = 0; imageIndex < mImagesCS.size(); ++imageIndex)
1350     {
1351         stream->writeBool(mImagesCS[imageIndex].active);
1352         stream->writeInt(mImagesCS[imageIndex].logicalImageUnit);
1353     }
1354 
1355     stream->writeInt(mReadonlyImagesCS.size());
1356     for (size_t imageIndex = 0; imageIndex < mReadonlyImagesCS.size(); ++imageIndex)
1357     {
1358         stream->writeBool(mReadonlyImagesCS[imageIndex].active);
1359         stream->writeInt(mReadonlyImagesCS[imageIndex].logicalImageUnit);
1360     }
1361 
1362     stream->writeInt(mUsedComputeImageRange.low());
1363     stream->writeInt(mUsedComputeImageRange.high());
1364     stream->writeInt(mUsedComputeReadonlyImageRange.low());
1365     stream->writeInt(mUsedComputeReadonlyImageRange.high());
1366     stream->writeInt(mUsedComputeAtomicCounterRange.low());
1367     stream->writeInt(mUsedComputeAtomicCounterRange.high());
1368 
1369     stream->writeInt(mD3DShaderStorageBlocks.size());
1370     for (const D3DInterfaceBlock &shaderStorageBlock : mD3DShaderStorageBlocks)
1371     {
1372         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1373         {
1374             stream->writeIntOrNegOne(shaderStorageBlock.mShaderRegisterIndexes[shaderType]);
1375         }
1376     }
1377 
1378     stream->writeInt(mImage2DUniforms.size());
1379     for (const sh::ShaderVariable &image2DUniform : mImage2DUniforms)
1380     {
1381         gl::WriteShaderVar(stream, image2DUniform);
1382     }
1383 
1384     for (unsigned int ii = 0; ii < gl::IMPLEMENTATION_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS; ++ii)
1385     {
1386         stream->writeInt(mComputeAtomicCounterBufferRegisterIndices[ii]);
1387     }
1388 
1389     stream->writeInt(mD3DUniforms.size());
1390     for (const D3DUniform *uniform : mD3DUniforms)
1391     {
1392         // Type, name and arraySize are redundant, so aren't stored in the binary.
1393         stream->writeEnum(uniform->regType);
1394         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1395         {
1396             stream->writeIntOrNegOne(uniform->mShaderRegisterIndexes[shaderType]);
1397         }
1398         stream->writeInt(uniform->registerCount);
1399         stream->writeInt(uniform->registerElement);
1400     }
1401 
1402     stream->writeInt(mD3DUniformBlocks.size());
1403     for (const D3DUniformBlock &uniformBlock : mD3DUniformBlocks)
1404     {
1405         for (gl::ShaderType shaderType : gl::AllShaderTypes())
1406         {
1407             stream->writeIntOrNegOne(uniformBlock.mShaderRegisterIndexes[shaderType]);
1408             stream->writeBool(uniformBlock.mUseStructuredBuffers[shaderType]);
1409             stream->writeInt(uniformBlock.mByteWidths[shaderType]);
1410             stream->writeInt(uniformBlock.mStructureByteStrides[shaderType]);
1411         }
1412     }
1413 
1414     stream->writeInt(mStreamOutVaryings.size());
1415     for (const D3DVarying &varying : mStreamOutVaryings)
1416     {
1417         stream->writeString(varying.semanticName);
1418         stream->writeInt(varying.semanticIndex);
1419         stream->writeInt(varying.componentCount);
1420         stream->writeInt(varying.outputSlot);
1421     }
1422 
1423     for (gl::ShaderType shaderType : gl::AllShaderTypes())
1424     {
1425         stream->writeString(mShaderHLSL[shaderType]);
1426         stream->writeBytes(reinterpret_cast<unsigned char *>(&mShaderWorkarounds[shaderType]),
1427                            sizeof(angle::CompilerWorkaroundsD3D));
1428     }
1429 
1430     stream->writeBool(mUsesFragDepth);
1431     stream->writeBool(mHasANGLEMultiviewEnabled);
1432     stream->writeBool(mUsesVertexID);
1433     stream->writeBool(mUsesViewID);
1434     stream->writeBool(mUsesPointSize);
1435     stream->writeBool(mUsesFlatInterpolation);
1436 
1437     const std::vector<PixelShaderOutputVariable> &pixelShaderKey = mPixelShaderKey;
1438     stream->writeInt(pixelShaderKey.size());
1439     for (size_t pixelShaderKeyIndex = 0; pixelShaderKeyIndex < pixelShaderKey.size();
1440          pixelShaderKeyIndex++)
1441     {
1442         const PixelShaderOutputVariable &variable = pixelShaderKey[pixelShaderKeyIndex];
1443         stream->writeInt(variable.type);
1444         stream->writeString(variable.name);
1445         stream->writeString(variable.source);
1446         stream->writeInt(variable.outputLocation);
1447         stream->writeInt(variable.outputIndex);
1448     }
1449 
1450     stream->writeString(mGeometryShaderPreamble);
1451 
1452     stream->writeInt(mVertexExecutables.size());
1453     for (size_t vertexExecutableIndex = 0; vertexExecutableIndex < mVertexExecutables.size();
1454          vertexExecutableIndex++)
1455     {
1456         VertexExecutable *vertexExecutable = mVertexExecutables[vertexExecutableIndex].get();
1457 
1458         const gl::InputLayout &inputLayout = vertexExecutable->inputs();
1459         stream->writeInt(inputLayout.size());
1460 
1461         for (size_t inputIndex = 0; inputIndex < inputLayout.size(); inputIndex++)
1462         {
1463             stream->writeEnum(inputLayout[inputIndex]);
1464         }
1465 
1466         size_t vertexShaderSize = vertexExecutable->shaderExecutable()->getLength();
1467         stream->writeInt(vertexShaderSize);
1468 
1469         const uint8_t *vertexBlob = vertexExecutable->shaderExecutable()->getFunction();
1470         stream->writeBytes(vertexBlob, vertexShaderSize);
1471     }
1472 
1473     stream->writeInt(mPixelExecutables.size());
1474     for (size_t pixelExecutableIndex = 0; pixelExecutableIndex < mPixelExecutables.size();
1475          pixelExecutableIndex++)
1476     {
1477         PixelExecutable *pixelExecutable = mPixelExecutables[pixelExecutableIndex].get();
1478 
1479         const std::vector<GLenum> &outputs = pixelExecutable->outputSignature();
1480         stream->writeInt(outputs.size());
1481         for (size_t outputIndex = 0; outputIndex < outputs.size(); outputIndex++)
1482         {
1483             stream->writeInt(outputs[outputIndex]);
1484         }
1485 
1486         size_t pixelShaderSize = pixelExecutable->shaderExecutable()->getLength();
1487         stream->writeInt(pixelShaderSize);
1488 
1489         const uint8_t *pixelBlob = pixelExecutable->shaderExecutable()->getFunction();
1490         stream->writeBytes(pixelBlob, pixelShaderSize);
1491     }
1492 
1493     for (auto const &geometryExecutable : mGeometryExecutables)
1494     {
1495         if (!geometryExecutable)
1496         {
1497             stream->writeInt<size_t>(0);
1498             continue;
1499         }
1500 
1501         size_t geometryShaderSize = geometryExecutable->getLength();
1502         stream->writeInt(geometryShaderSize);
1503         stream->writeBytes(geometryExecutable->getFunction(), geometryShaderSize);
1504     }
1505 
1506     stream->writeInt(mComputeExecutables.size());
1507     for (size_t computeExecutableIndex = 0; computeExecutableIndex < mComputeExecutables.size();
1508          computeExecutableIndex++)
1509     {
1510         ComputeExecutable *computeExecutable = mComputeExecutables[computeExecutableIndex].get();
1511 
1512         const gl::ImageUnitTextureTypeMap signatures = computeExecutable->signature();
1513         stream->writeInt(signatures.size());
1514         for (const auto &signature : signatures)
1515         {
1516             stream->writeInt(signature.first);
1517             stream->writeEnum(signature.second);
1518         }
1519 
1520         size_t computeShaderSize = computeExecutable->shaderExecutable()->getLength();
1521         stream->writeInt(computeShaderSize);
1522 
1523         const uint8_t *computeBlob = computeExecutable->shaderExecutable()->getFunction();
1524         stream->writeBytes(computeBlob, computeShaderSize);
1525     }
1526 
1527     stream->writeInt(mComputeShaderImage2DBindLayoutCache.size());
1528     for (auto &image2DBindLayout : mComputeShaderImage2DBindLayoutCache)
1529     {
1530         stream->writeInt(image2DBindLayout.first);
1531     }
1532 }
1533 
setBinaryRetrievableHint(bool)1534 void ProgramD3D::setBinaryRetrievableHint(bool /* retrievable */) {}
1535 
setSeparable(bool)1536 void ProgramD3D::setSeparable(bool /* separable */) {}
1537 
getPixelExecutableForCachedOutputLayout(d3d::Context * context,ShaderExecutableD3D ** outExecutable,gl::InfoLog * infoLog)1538 angle::Result ProgramD3D::getPixelExecutableForCachedOutputLayout(
1539     d3d::Context *context,
1540     ShaderExecutableD3D **outExecutable,
1541     gl::InfoLog *infoLog)
1542 {
1543     if (mCachedPixelExecutableIndex.valid())
1544     {
1545         *outExecutable = mPixelExecutables[mCachedPixelExecutableIndex.value()]->shaderExecutable();
1546         return angle::Result::Continue;
1547     }
1548 
1549     std::string finalPixelHLSL = mDynamicHLSL->generatePixelShaderForOutputSignature(
1550         mShaderHLSL[gl::ShaderType::Fragment], mPixelShaderKey, mUsesFragDepth,
1551         mPixelShaderOutputLayoutCache);
1552 
1553     // Generate new pixel executable
1554     ShaderExecutableD3D *pixelExecutable = nullptr;
1555 
1556     gl::InfoLog tempInfoLog;
1557     gl::InfoLog *currentInfoLog = infoLog ? infoLog : &tempInfoLog;
1558 
1559     ANGLE_TRY(mRenderer->compileToExecutable(
1560         context, *currentInfoLog, finalPixelHLSL, gl::ShaderType::Fragment, mStreamOutVaryings,
1561         (mState.getTransformFeedbackBufferMode() == GL_SEPARATE_ATTRIBS),
1562         mShaderWorkarounds[gl::ShaderType::Fragment], &pixelExecutable));
1563 
1564     if (pixelExecutable)
1565     {
1566         mPixelExecutables.push_back(std::unique_ptr<PixelExecutable>(
1567             new PixelExecutable(mPixelShaderOutputLayoutCache, pixelExecutable)));
1568         mCachedPixelExecutableIndex = mPixelExecutables.size() - 1;
1569     }
1570     else if (!infoLog)
1571     {
1572         ERR() << "Error compiling dynamic pixel executable:" << std::endl
1573               << tempInfoLog.str() << std::endl;
1574     }
1575 
1576     *outExecutable = pixelExecutable;
1577     return angle::Result::Continue;
1578 }
1579 
getVertexExecutableForCachedInputLayout(d3d::Context * context,ShaderExecutableD3D ** outExectuable,gl::InfoLog * infoLog)1580 angle::Result ProgramD3D::getVertexExecutableForCachedInputLayout(
1581     d3d::Context *context,
1582     ShaderExecutableD3D **outExectuable,
1583     gl::InfoLog *infoLog)
1584 {
1585     if (mCachedVertexExecutableIndex.valid())
1586     {
1587         *outExectuable =
1588             mVertexExecutables[mCachedVertexExecutableIndex.value()]->shaderExecutable();
1589         return angle::Result::Continue;
1590     }
1591 
1592     // Generate new dynamic layout with attribute conversions
1593     std::string finalVertexHLSL = mDynamicHLSL->generateVertexShaderForInputLayout(
1594         mShaderHLSL[gl::ShaderType::Vertex], mCachedInputLayout, mState.getProgramInputs());
1595 
1596     // Generate new vertex executable
1597     ShaderExecutableD3D *vertexExecutable = nullptr;
1598 
1599     gl::InfoLog tempInfoLog;
1600     gl::InfoLog *currentInfoLog = infoLog ? infoLog : &tempInfoLog;
1601 
1602     ANGLE_TRY(mRenderer->compileToExecutable(
1603         context, *currentInfoLog, finalVertexHLSL, gl::ShaderType::Vertex, mStreamOutVaryings,
1604         (mState.getTransformFeedbackBufferMode() == GL_SEPARATE_ATTRIBS),
1605         mShaderWorkarounds[gl::ShaderType::Vertex], &vertexExecutable));
1606 
1607     if (vertexExecutable)
1608     {
1609         mVertexExecutables.push_back(std::unique_ptr<VertexExecutable>(
1610             new VertexExecutable(mCachedInputLayout, mCachedVertexSignature, vertexExecutable)));
1611         mCachedVertexExecutableIndex = mVertexExecutables.size() - 1;
1612     }
1613     else if (!infoLog)
1614     {
1615         ERR() << "Error compiling dynamic vertex executable:" << std::endl
1616               << tempInfoLog.str() << std::endl;
1617     }
1618 
1619     *outExectuable = vertexExecutable;
1620     return angle::Result::Continue;
1621 }
1622 
getGeometryExecutableForPrimitiveType(d3d::Context * context,const gl::State & state,gl::PrimitiveMode drawMode,ShaderExecutableD3D ** outExecutable,gl::InfoLog * infoLog)1623 angle::Result ProgramD3D::getGeometryExecutableForPrimitiveType(d3d::Context *context,
1624                                                                 const gl::State &state,
1625                                                                 gl::PrimitiveMode drawMode,
1626                                                                 ShaderExecutableD3D **outExecutable,
1627                                                                 gl::InfoLog *infoLog)
1628 {
1629     if (outExecutable)
1630     {
1631         *outExecutable = nullptr;
1632     }
1633 
1634     // Return a null shader if the current rendering doesn't use a geometry shader
1635     if (!usesGeometryShader(state, drawMode))
1636     {
1637         return angle::Result::Continue;
1638     }
1639 
1640     gl::PrimitiveMode geometryShaderType = GetGeometryShaderTypeFromDrawMode(drawMode);
1641 
1642     if (mGeometryExecutables[geometryShaderType])
1643     {
1644         if (outExecutable)
1645         {
1646             *outExecutable = mGeometryExecutables[geometryShaderType].get();
1647         }
1648         return angle::Result::Continue;
1649     }
1650     const gl::Caps &caps     = state.getCaps();
1651     std::string geometryHLSL = mDynamicHLSL->generateGeometryShaderHLSL(
1652         caps, geometryShaderType, mState, mRenderer->presentPathFastEnabled(),
1653         mHasANGLEMultiviewEnabled, mRenderer->canSelectViewInVertexShader(),
1654         usesGeometryShaderForPointSpriteEmulation(), mGeometryShaderPreamble);
1655 
1656     gl::InfoLog tempInfoLog;
1657     gl::InfoLog *currentInfoLog = infoLog ? infoLog : &tempInfoLog;
1658 
1659     ShaderExecutableD3D *geometryExecutable = nullptr;
1660     angle::Result result                    = mRenderer->compileToExecutable(
1661         context, *currentInfoLog, geometryHLSL, gl::ShaderType::Geometry, mStreamOutVaryings,
1662         (mState.getTransformFeedbackBufferMode() == GL_SEPARATE_ATTRIBS),
1663         angle::CompilerWorkaroundsD3D(), &geometryExecutable);
1664 
1665     if (!infoLog && result == angle::Result::Stop)
1666     {
1667         ERR() << "Error compiling dynamic geometry executable:" << std::endl
1668               << tempInfoLog.str() << std::endl;
1669     }
1670 
1671     if (geometryExecutable != nullptr)
1672     {
1673         mGeometryExecutables[geometryShaderType].reset(geometryExecutable);
1674     }
1675 
1676     if (outExecutable)
1677     {
1678         *outExecutable = mGeometryExecutables[geometryShaderType].get();
1679     }
1680     return result;
1681 }
1682 
1683 class ProgramD3D::GetVertexExecutableTask : public ProgramD3D::GetExecutableTask
1684 {
1685   public:
GetVertexExecutableTask(ProgramD3D * program)1686     GetVertexExecutableTask(ProgramD3D *program) : GetExecutableTask(program) {}
run()1687     angle::Result run() override
1688     {
1689         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::GetVertexExecutableTask::run");
1690         if (!mProgram->mState.getAttachedShader(gl::ShaderType::Vertex))
1691         {
1692             return angle::Result::Continue;
1693         }
1694 
1695         mProgram->updateCachedInputLayoutFromShader();
1696 
1697         ANGLE_TRY(mProgram->getVertexExecutableForCachedInputLayout(this, &mExecutable, &mInfoLog));
1698 
1699         return angle::Result::Continue;
1700     }
1701 };
1702 
updateCachedInputLayoutFromShader()1703 void ProgramD3D::updateCachedInputLayoutFromShader()
1704 {
1705     GetDefaultInputLayoutFromShader(mState.getAttachedShader(gl::ShaderType::Vertex),
1706                                     &mCachedInputLayout);
1707     VertexExecutable::getSignature(mRenderer, mCachedInputLayout, &mCachedVertexSignature);
1708     updateCachedVertexExecutableIndex();
1709 }
1710 
1711 class ProgramD3D::GetPixelExecutableTask : public ProgramD3D::GetExecutableTask
1712 {
1713   public:
GetPixelExecutableTask(ProgramD3D * program)1714     GetPixelExecutableTask(ProgramD3D *program) : GetExecutableTask(program) {}
run()1715     angle::Result run() override
1716     {
1717         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::GetPixelExecutableTask::run");
1718         if (!mProgram->mState.getAttachedShader(gl::ShaderType::Fragment))
1719         {
1720             return angle::Result::Continue;
1721         }
1722 
1723         mProgram->updateCachedOutputLayoutFromShader();
1724 
1725         ANGLE_TRY(mProgram->getPixelExecutableForCachedOutputLayout(this, &mExecutable, &mInfoLog));
1726 
1727         return angle::Result::Continue;
1728     }
1729 };
1730 
updateCachedOutputLayoutFromShader()1731 void ProgramD3D::updateCachedOutputLayoutFromShader()
1732 {
1733     GetDefaultOutputLayoutFromShader(mPixelShaderKey, &mPixelShaderOutputLayoutCache);
1734     updateCachedPixelExecutableIndex();
1735 }
1736 
updateCachedImage2DBindLayoutFromComputeShader()1737 void ProgramD3D::updateCachedImage2DBindLayoutFromComputeShader()
1738 {
1739     GetDefaultImage2DBindLayoutFromComputeShader(mImage2DUniforms,
1740                                                  &mComputeShaderImage2DBindLayoutCache);
1741     updateCachedComputeExecutableIndex();
1742 }
1743 
1744 class ProgramD3D::GetGeometryExecutableTask : public ProgramD3D::GetExecutableTask
1745 {
1746   public:
GetGeometryExecutableTask(ProgramD3D * program,const gl::State & state)1747     GetGeometryExecutableTask(ProgramD3D *program, const gl::State &state)
1748         : GetExecutableTask(program), mState(state)
1749     {}
1750 
run()1751     angle::Result run() override
1752     {
1753         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::GetGeometryExecutableTask::run");
1754         // Auto-generate the geometry shader here, if we expect to be using point rendering in
1755         // D3D11.
1756         if (mProgram->usesGeometryShader(mState, gl::PrimitiveMode::Points))
1757         {
1758             ANGLE_TRY(mProgram->getGeometryExecutableForPrimitiveType(
1759                 this, mState, gl::PrimitiveMode::Points, &mExecutable, &mInfoLog));
1760         }
1761 
1762         return angle::Result::Continue;
1763     }
1764 
1765   private:
1766     const gl::State &mState;
1767 };
1768 
1769 class ProgramD3D::GetComputeExecutableTask : public ProgramD3D::GetExecutableTask
1770 {
1771   public:
GetComputeExecutableTask(ProgramD3D * program)1772     GetComputeExecutableTask(ProgramD3D *program) : GetExecutableTask(program) {}
run()1773     angle::Result run() override
1774     {
1775         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::GetComputeExecutableTask::run");
1776         mProgram->updateCachedImage2DBindLayoutFromComputeShader();
1777         ShaderExecutableD3D *computeExecutable = nullptr;
1778         ANGLE_TRY(mProgram->getComputeExecutableForImage2DBindLayout(this, &computeExecutable,
1779                                                                      &mInfoLog));
1780 
1781         return computeExecutable ? angle::Result::Continue : angle::Result::Incomplete;
1782     }
1783 };
1784 
1785 // The LinkEvent implementation for linking a rendering(VS, FS, GS) program.
1786 class ProgramD3D::GraphicsProgramLinkEvent final : public LinkEvent
1787 {
1788   public:
GraphicsProgramLinkEvent(gl::InfoLog & infoLog,std::shared_ptr<WorkerThreadPool> workerPool,std::shared_ptr<ProgramD3D::GetVertexExecutableTask> vertexTask,std::shared_ptr<ProgramD3D::GetPixelExecutableTask> pixelTask,std::shared_ptr<ProgramD3D::GetGeometryExecutableTask> geometryTask,bool useGS,const ShaderD3D * vertexShader,const ShaderD3D * fragmentShader)1789     GraphicsProgramLinkEvent(gl::InfoLog &infoLog,
1790                              std::shared_ptr<WorkerThreadPool> workerPool,
1791                              std::shared_ptr<ProgramD3D::GetVertexExecutableTask> vertexTask,
1792                              std::shared_ptr<ProgramD3D::GetPixelExecutableTask> pixelTask,
1793                              std::shared_ptr<ProgramD3D::GetGeometryExecutableTask> geometryTask,
1794                              bool useGS,
1795                              const ShaderD3D *vertexShader,
1796                              const ShaderD3D *fragmentShader)
1797         : mInfoLog(infoLog),
1798           mVertexTask(vertexTask),
1799           mPixelTask(pixelTask),
1800           mGeometryTask(geometryTask),
1801           mWaitEvents({{std::shared_ptr<WaitableEvent>(
1802                             angle::WorkerThreadPool::PostWorkerTask(workerPool, mVertexTask)),
1803                         std::shared_ptr<WaitableEvent>(
1804                             angle::WorkerThreadPool::PostWorkerTask(workerPool, mPixelTask)),
1805                         std::shared_ptr<WaitableEvent>(
1806                             angle::WorkerThreadPool::PostWorkerTask(workerPool, mGeometryTask))}}),
1807           mUseGS(useGS),
1808           mVertexShader(vertexShader),
1809           mFragmentShader(fragmentShader)
1810     {}
1811 
wait(const gl::Context * context)1812     angle::Result wait(const gl::Context *context) override
1813     {
1814         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::GraphicsProgramLinkEvent::wait");
1815         WaitableEvent::WaitMany(&mWaitEvents);
1816 
1817         ANGLE_TRY(checkTask(context, mVertexTask.get()));
1818         ANGLE_TRY(checkTask(context, mPixelTask.get()));
1819         ANGLE_TRY(checkTask(context, mGeometryTask.get()));
1820 
1821         if (mVertexTask->getResult() == angle::Result::Incomplete ||
1822             mPixelTask->getResult() == angle::Result::Incomplete ||
1823             mGeometryTask->getResult() == angle::Result::Incomplete)
1824         {
1825             return angle::Result::Incomplete;
1826         }
1827 
1828         ShaderExecutableD3D *defaultVertexExecutable = mVertexTask->getExecutable();
1829         ShaderExecutableD3D *defaultPixelExecutable  = mPixelTask->getExecutable();
1830         ShaderExecutableD3D *pointGS                 = mGeometryTask->getExecutable();
1831 
1832         if (mUseGS && pointGS)
1833         {
1834             // Geometry shaders are currently only used internally, so there is no corresponding
1835             // shader object at the interface level. For now the geometry shader debug info is
1836             // prepended to the vertex shader.
1837             mVertexShader->appendDebugInfo("// GEOMETRY SHADER BEGIN\n\n");
1838             mVertexShader->appendDebugInfo(pointGS->getDebugInfo());
1839             mVertexShader->appendDebugInfo("\nGEOMETRY SHADER END\n\n\n");
1840         }
1841 
1842         if (defaultVertexExecutable)
1843         {
1844             mVertexShader->appendDebugInfo(defaultVertexExecutable->getDebugInfo());
1845         }
1846 
1847         if (defaultPixelExecutable)
1848         {
1849             mFragmentShader->appendDebugInfo(defaultPixelExecutable->getDebugInfo());
1850         }
1851 
1852         bool isLinked = (defaultVertexExecutable && defaultPixelExecutable && (!mUseGS || pointGS));
1853         if (!isLinked)
1854         {
1855             mInfoLog << "Failed to create D3D Shaders";
1856         }
1857         return isLinked ? angle::Result::Continue : angle::Result::Incomplete;
1858     }
1859 
isLinking()1860     bool isLinking() override
1861     {
1862         for (auto &event : mWaitEvents)
1863         {
1864             if (!event->isReady())
1865             {
1866                 return true;
1867             }
1868         }
1869         return false;
1870     }
1871 
1872   private:
checkTask(const gl::Context * context,ProgramD3D::GetExecutableTask * task)1873     angle::Result checkTask(const gl::Context *context, ProgramD3D::GetExecutableTask *task)
1874     {
1875         if (!task->getInfoLog().empty())
1876         {
1877             mInfoLog << task->getInfoLog().str();
1878         }
1879 
1880         // Continue and Incomplete are not errors. For Stop, pass the error to the ContextD3D.
1881         if (task->getResult() != angle::Result::Stop)
1882         {
1883             return angle::Result::Continue;
1884         }
1885 
1886         ContextD3D *contextD3D = GetImplAs<ContextD3D>(context);
1887         task->popError(contextD3D);
1888         return angle::Result::Stop;
1889     }
1890 
1891     gl::InfoLog &mInfoLog;
1892     std::shared_ptr<ProgramD3D::GetVertexExecutableTask> mVertexTask;
1893     std::shared_ptr<ProgramD3D::GetPixelExecutableTask> mPixelTask;
1894     std::shared_ptr<ProgramD3D::GetGeometryExecutableTask> mGeometryTask;
1895     std::array<std::shared_ptr<WaitableEvent>, 3> mWaitEvents;
1896     bool mUseGS;
1897     const ShaderD3D *mVertexShader;
1898     const ShaderD3D *mFragmentShader;
1899 };
1900 
1901 // The LinkEvent implementation for linking a computing program.
1902 class ProgramD3D::ComputeProgramLinkEvent final : public LinkEvent
1903 {
1904   public:
ComputeProgramLinkEvent(gl::InfoLog & infoLog,std::shared_ptr<ProgramD3D::GetComputeExecutableTask> computeTask,std::shared_ptr<WaitableEvent> event)1905     ComputeProgramLinkEvent(gl::InfoLog &infoLog,
1906                             std::shared_ptr<ProgramD3D::GetComputeExecutableTask> computeTask,
1907                             std::shared_ptr<WaitableEvent> event)
1908         : mInfoLog(infoLog), mComputeTask(computeTask), mWaitEvent(event)
1909     {}
1910 
isLinking()1911     bool isLinking() override { return !mWaitEvent->isReady(); }
1912 
wait(const gl::Context * context)1913     angle::Result wait(const gl::Context *context) override
1914     {
1915         ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::ComputeProgramLinkEvent::wait");
1916         mWaitEvent->wait();
1917 
1918         angle::Result result = mComputeTask->getResult();
1919         if (result != angle::Result::Continue)
1920         {
1921             mInfoLog << "Failed to create D3D compute shader.";
1922         }
1923         return result;
1924     }
1925 
1926   private:
1927     gl::InfoLog &mInfoLog;
1928     std::shared_ptr<ProgramD3D::GetComputeExecutableTask> mComputeTask;
1929     std::shared_ptr<WaitableEvent> mWaitEvent;
1930 };
1931 
compileProgramExecutables(const gl::Context * context,gl::InfoLog & infoLog)1932 std::unique_ptr<LinkEvent> ProgramD3D::compileProgramExecutables(const gl::Context *context,
1933                                                                  gl::InfoLog &infoLog)
1934 {
1935     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::compileProgramExecutables");
1936     // Ensure the compiler is initialized to avoid race conditions.
1937     angle::Result result = mRenderer->ensureHLSLCompilerInitialized(GetImplAs<ContextD3D>(context));
1938     if (result != angle::Result::Continue)
1939     {
1940         return std::make_unique<LinkEventDone>(result);
1941     }
1942 
1943     auto vertexTask   = std::make_shared<GetVertexExecutableTask>(this);
1944     auto pixelTask    = std::make_shared<GetPixelExecutableTask>(this);
1945     auto geometryTask = std::make_shared<GetGeometryExecutableTask>(this, context->getState());
1946     bool useGS        = usesGeometryShader(context->getState(), gl::PrimitiveMode::Points);
1947     gl::Shader *vertexShader         = mState.getAttachedShader(gl::ShaderType::Vertex);
1948     gl::Shader *fragmentShader       = mState.getAttachedShader(gl::ShaderType::Fragment);
1949     const ShaderD3D *vertexShaderD3D = vertexShader ? GetImplAs<ShaderD3D>(vertexShader) : nullptr;
1950     const ShaderD3D *fragmentShaderD3D =
1951         fragmentShader ? GetImplAs<ShaderD3D>(fragmentShader) : nullptr;
1952 
1953     return std::make_unique<GraphicsProgramLinkEvent>(infoLog, context->getWorkerThreadPool(),
1954                                                       vertexTask, pixelTask, geometryTask, useGS,
1955                                                       vertexShaderD3D, fragmentShaderD3D);
1956 }
1957 
compileComputeExecutable(const gl::Context * context,gl::InfoLog & infoLog)1958 std::unique_ptr<LinkEvent> ProgramD3D::compileComputeExecutable(const gl::Context *context,
1959                                                                 gl::InfoLog &infoLog)
1960 {
1961     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::compileComputeExecutable");
1962     // Ensure the compiler is initialized to avoid race conditions.
1963     angle::Result result = mRenderer->ensureHLSLCompilerInitialized(GetImplAs<ContextD3D>(context));
1964     if (result != angle::Result::Continue)
1965     {
1966         return std::make_unique<LinkEventDone>(result);
1967     }
1968     auto computeTask = std::make_shared<GetComputeExecutableTask>(this);
1969 
1970     std::shared_ptr<WaitableEvent> waitableEvent;
1971 
1972     // TODO(jie.a.chen@intel.com): Fix the flaky bug.
1973     // http://anglebug.com/3349
1974     bool compileInParallel = false;
1975     if (!compileInParallel)
1976     {
1977         (*computeTask)();
1978         waitableEvent = std::make_shared<WaitableEventDone>();
1979     }
1980     else
1981     {
1982         waitableEvent =
1983             WorkerThreadPool::PostWorkerTask(context->getWorkerThreadPool(), computeTask);
1984     }
1985 
1986     return std::make_unique<ComputeProgramLinkEvent>(infoLog, computeTask, waitableEvent);
1987 }
1988 
getComputeExecutableForImage2DBindLayout(d3d::Context * context,ShaderExecutableD3D ** outExecutable,gl::InfoLog * infoLog)1989 angle::Result ProgramD3D::getComputeExecutableForImage2DBindLayout(
1990     d3d::Context *context,
1991     ShaderExecutableD3D **outExecutable,
1992     gl::InfoLog *infoLog)
1993 {
1994     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::getComputeExecutableForImage2DBindLayout");
1995     if (mCachedComputeExecutableIndex.valid())
1996     {
1997         *outExecutable =
1998             mComputeExecutables[mCachedComputeExecutableIndex.value()]->shaderExecutable();
1999         return angle::Result::Continue;
2000     }
2001 
2002     std::string finalComputeHLSL = mDynamicHLSL->generateComputeShaderForImage2DBindSignature(
2003         context, *this, mState, mImage2DUniforms, mComputeShaderImage2DBindLayoutCache);
2004 
2005     // Generate new compute executable
2006     ShaderExecutableD3D *computeExecutable = nullptr;
2007 
2008     gl::InfoLog tempInfoLog;
2009     gl::InfoLog *currentInfoLog = infoLog ? infoLog : &tempInfoLog;
2010 
2011     ANGLE_TRY(mRenderer->compileToExecutable(
2012         context, *currentInfoLog, finalComputeHLSL, gl::ShaderType::Compute,
2013         std::vector<D3DVarying>(), false, angle::CompilerWorkaroundsD3D(), &computeExecutable));
2014 
2015     if (computeExecutable)
2016     {
2017         mComputeExecutables.push_back(std::unique_ptr<ComputeExecutable>(
2018             new ComputeExecutable(mComputeShaderImage2DBindLayoutCache,
2019                                   std::unique_ptr<ShaderExecutableD3D>(computeExecutable))));
2020         mCachedComputeExecutableIndex = mComputeExecutables.size() - 1;
2021     }
2022     else if (!infoLog)
2023     {
2024         ERR() << "Error compiling dynamic compute executable:" << std::endl
2025               << tempInfoLog.str() << std::endl;
2026     }
2027     *outExecutable = computeExecutable;
2028 
2029     return angle::Result::Continue;
2030 }
2031 
link(const gl::Context * context,const gl::ProgramLinkedResources & resources,gl::InfoLog & infoLog,const gl::ProgramMergedVaryings &)2032 std::unique_ptr<LinkEvent> ProgramD3D::link(const gl::Context *context,
2033                                             const gl::ProgramLinkedResources &resources,
2034                                             gl::InfoLog &infoLog,
2035                                             const gl::ProgramMergedVaryings & /*mergedVaryings*/)
2036 {
2037     ANGLE_TRACE_EVENT0("gpu.angle", "ProgramD3D::link");
2038     const auto &data = context->getState();
2039 
2040     reset();
2041 
2042     gl::Shader *computeShader = mState.getAttachedShader(gl::ShaderType::Compute);
2043     if (computeShader)
2044     {
2045         mShaderSamplers[gl::ShaderType::Compute].resize(
2046             data.getCaps().maxShaderTextureImageUnits[gl::ShaderType::Compute]);
2047         mImagesCS.resize(data.getCaps().maxImageUnits);
2048         mReadonlyImagesCS.resize(data.getCaps().maxImageUnits);
2049 
2050         mShaderUniformsDirty.set(gl::ShaderType::Compute);
2051 
2052         linkResources(resources);
2053 
2054         for (const sh::ShaderVariable &uniform : computeShader->getUniforms())
2055         {
2056             if (gl::IsImageType(uniform.type) && gl::IsImage2DType(uniform.type))
2057             {
2058                 mImage2DUniforms.push_back(uniform);
2059             }
2060         }
2061 
2062         defineUniformsAndAssignRegisters();
2063 
2064         return compileComputeExecutable(context, infoLog);
2065     }
2066     else
2067     {
2068         gl::ShaderMap<const ShaderD3D *> shadersD3D = {};
2069         for (gl::ShaderType shaderType : gl::kAllGraphicsShaderTypes)
2070         {
2071             if (mState.getAttachedShader(shaderType))
2072             {
2073                 shadersD3D[shaderType] = GetImplAs<ShaderD3D>(mState.getAttachedShader(shaderType));
2074 
2075                 mShaderSamplers[shaderType].resize(
2076                     data.getCaps().maxShaderTextureImageUnits[shaderType]);
2077 
2078                 shadersD3D[shaderType]->generateWorkarounds(&mShaderWorkarounds[shaderType]);
2079 
2080                 mShaderUniformsDirty.set(shaderType);
2081 
2082                 const std::set<std::string> &slowCompilingUniformBlockSet =
2083                     shadersD3D[shaderType]->getSlowCompilingUniformBlockSet();
2084                 if (slowCompilingUniformBlockSet.size() > 0)
2085                 {
2086                     std::ostringstream stream;
2087                     stream << "You could get a better shader compiling performance if you re-write"
2088                            << " the uniform block(s)\n[ ";
2089                     for (const std::string &str : slowCompilingUniformBlockSet)
2090                     {
2091                         stream << str << " ";
2092                     }
2093                     stream << "]\nin the " << gl::GetShaderTypeString(shaderType) << " shader.\n";
2094 
2095                     stream << "You could get more details from "
2096                               "https://chromium.googlesource.com/angle/angle/+/refs/heads/master/"
2097                               "src/libANGLE/renderer/d3d/d3d11/"
2098                               "UniformBlockToStructuredBufferTranslation.md\n";
2099                     ANGLE_PERF_WARNING(context->getState().getDebug(), GL_DEBUG_SEVERITY_MEDIUM,
2100                                        stream.str().c_str());
2101                 }
2102             }
2103         }
2104 
2105         if (mRenderer->getNativeLimitations().noFrontFacingSupport)
2106         {
2107             const ShaderD3D *fragmentShader = shadersD3D[gl::ShaderType::Fragment];
2108             if (fragmentShader && fragmentShader->usesFrontFacing())
2109             {
2110                 infoLog << "The current renderer doesn't support gl_FrontFacing";
2111                 return std::make_unique<LinkEventDone>(angle::Result::Incomplete);
2112             }
2113         }
2114 
2115         const gl::VaryingPacking &varyingPacking =
2116             resources.varyingPacking.getOutputPacking(gl::ShaderType::Vertex);
2117 
2118         ProgramD3DMetadata metadata(mRenderer, shadersD3D, context->getClientType());
2119         BuiltinVaryingsD3D builtins(metadata, varyingPacking);
2120 
2121         mDynamicHLSL->generateShaderLinkHLSL(context->getCaps(), mState, metadata, varyingPacking,
2122                                              builtins, &mShaderHLSL);
2123 
2124         const ShaderD3D *vertexShader = shadersD3D[gl::ShaderType::Vertex];
2125         mUsesPointSize                = vertexShader && vertexShader->usesPointSize();
2126         mDynamicHLSL->getPixelShaderOutputKey(data, mState, metadata, &mPixelShaderKey);
2127         mUsesFragDepth            = metadata.usesFragDepth();
2128         mUsesVertexID             = metadata.usesVertexID();
2129         mUsesViewID               = metadata.usesViewID();
2130         mHasANGLEMultiviewEnabled = metadata.hasANGLEMultiviewEnabled();
2131 
2132         // Cache if we use flat shading
2133         mUsesFlatInterpolation = FindFlatInterpolationVarying(mState.getAttachedShaders());
2134 
2135         if (mRenderer->getMajorShaderModel() >= 4)
2136         {
2137             mGeometryShaderPreamble = mDynamicHLSL->generateGeometryShaderPreamble(
2138                 varyingPacking, builtins, mHasANGLEMultiviewEnabled,
2139                 metadata.canSelectViewInVertexShader());
2140         }
2141 
2142         initAttribLocationsToD3DSemantic();
2143 
2144         defineUniformsAndAssignRegisters();
2145 
2146         gatherTransformFeedbackVaryings(varyingPacking, builtins[gl::ShaderType::Vertex]);
2147 
2148         linkResources(resources);
2149 
2150         return compileProgramExecutables(context, infoLog);
2151     }
2152 }
2153 
validate(const gl::Caps &,gl::InfoLog *)2154 GLboolean ProgramD3D::validate(const gl::Caps & /*caps*/, gl::InfoLog * /*infoLog*/)
2155 {
2156     // TODO(jmadill): Do something useful here?
2157     return GL_TRUE;
2158 }
2159 
initializeShaderStorageBlocks()2160 void ProgramD3D::initializeShaderStorageBlocks()
2161 {
2162     if (mState.getShaderStorageBlocks().empty())
2163     {
2164         return;
2165     }
2166 
2167     ASSERT(mD3DShaderStorageBlocks.empty());
2168 
2169     // Assign registers and update sizes.
2170     gl::ShaderMap<const ShaderD3D *> shadersD3D = {};
2171     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2172     {
2173         shadersD3D[shaderType] = SafeGetImplAs<ShaderD3D>(mState.getAttachedShader(shaderType));
2174     }
2175 
2176     for (const gl::InterfaceBlock &shaderStorageBlock : mState.getShaderStorageBlocks())
2177     {
2178         unsigned int shaderStorageBlockElement =
2179             shaderStorageBlock.isArray ? shaderStorageBlock.arrayElement : 0;
2180 
2181         D3DInterfaceBlock d3dShaderStorageBlock;
2182 
2183         for (gl::ShaderType shaderType : gl::AllShaderTypes())
2184         {
2185             if (shaderStorageBlock.isActive(shaderType))
2186             {
2187                 ASSERT(shadersD3D[shaderType]);
2188                 unsigned int baseRegister =
2189                     shadersD3D[shaderType]->getShaderStorageBlockRegister(shaderStorageBlock.name);
2190                 d3dShaderStorageBlock.mShaderRegisterIndexes[shaderType] =
2191                     baseRegister + shaderStorageBlockElement;
2192             }
2193         }
2194 
2195         mD3DShaderStorageBlocks.push_back(d3dShaderStorageBlock);
2196     }
2197 }
2198 
initializeUniformBlocks()2199 void ProgramD3D::initializeUniformBlocks()
2200 {
2201     if (mState.getUniformBlocks().empty())
2202     {
2203         return;
2204     }
2205 
2206     ASSERT(mD3DUniformBlocks.empty());
2207 
2208     // Assign registers and update sizes.
2209     gl::ShaderMap<const ShaderD3D *> shadersD3D = {};
2210     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2211     {
2212         shadersD3D[shaderType] = SafeGetImplAs<ShaderD3D>(mState.getAttachedShader(shaderType));
2213     }
2214 
2215     for (const gl::InterfaceBlock &uniformBlock : mState.getUniformBlocks())
2216     {
2217         unsigned int uniformBlockElement = uniformBlock.isArray ? uniformBlock.arrayElement : 0;
2218 
2219         D3DUniformBlock d3dUniformBlock;
2220 
2221         for (gl::ShaderType shaderType : gl::AllShaderTypes())
2222         {
2223             if (uniformBlock.isActive(shaderType))
2224             {
2225                 ASSERT(shadersD3D[shaderType]);
2226                 unsigned int baseRegister =
2227                     shadersD3D[shaderType]->getUniformBlockRegister(uniformBlock.name);
2228                 d3dUniformBlock.mShaderRegisterIndexes[shaderType] =
2229                     baseRegister + uniformBlockElement;
2230                 bool useStructuredBuffer =
2231                     shadersD3D[shaderType]->shouldUniformBlockUseStructuredBuffer(
2232                         uniformBlock.name);
2233                 if (useStructuredBuffer)
2234                 {
2235                     d3dUniformBlock.mUseStructuredBuffers[shaderType] = true;
2236                     d3dUniformBlock.mByteWidths[shaderType]           = uniformBlock.dataSize;
2237                     d3dUniformBlock.mStructureByteStrides[shaderType] =
2238                         uniformBlock.firstFieldArraySize == 0u
2239                             ? uniformBlock.dataSize
2240                             : uniformBlock.dataSize / uniformBlock.firstFieldArraySize;
2241                 }
2242             }
2243         }
2244 
2245         mD3DUniformBlocks.push_back(d3dUniformBlock);
2246     }
2247 }
2248 
initializeUniformStorage(const gl::ShaderBitSet & availableShaderStages)2249 void ProgramD3D::initializeUniformStorage(const gl::ShaderBitSet &availableShaderStages)
2250 {
2251     // Compute total default block size
2252     gl::ShaderMap<unsigned int> shaderRegisters = {};
2253     for (const D3DUniform *d3dUniform : mD3DUniforms)
2254     {
2255         if (d3dUniform->isSampler())
2256         {
2257             continue;
2258         }
2259 
2260         for (gl::ShaderType shaderType : availableShaderStages)
2261         {
2262             if (d3dUniform->isReferencedByShader(shaderType))
2263             {
2264                 shaderRegisters[shaderType] = std::max(
2265                     shaderRegisters[shaderType],
2266                     d3dUniform->mShaderRegisterIndexes[shaderType] + d3dUniform->registerCount);
2267             }
2268         }
2269     }
2270 
2271     // We only reset uniform storages for the shader stages available in the program (attached
2272     // shaders in ProgramD3D::link() and linkedShaderStages in ProgramD3D::load()).
2273     for (gl::ShaderType shaderType : availableShaderStages)
2274     {
2275         mShaderUniformStorages[shaderType].reset(
2276             mRenderer->createUniformStorage(shaderRegisters[shaderType] * 16u));
2277     }
2278 
2279     // Iterate the uniforms again to assign data pointers to default block uniforms.
2280     for (D3DUniform *d3dUniform : mD3DUniforms)
2281     {
2282         if (d3dUniform->isSampler())
2283         {
2284             d3dUniform->mSamplerData.resize(d3dUniform->getArraySizeProduct(), 0);
2285             continue;
2286         }
2287 
2288         for (gl::ShaderType shaderType : availableShaderStages)
2289         {
2290             if (d3dUniform->isReferencedByShader(shaderType))
2291             {
2292                 d3dUniform->mShaderData[shaderType] =
2293                     mShaderUniformStorages[shaderType]->getDataPointer(
2294                         d3dUniform->mShaderRegisterIndexes[shaderType],
2295                         d3dUniform->registerElement);
2296             }
2297         }
2298     }
2299 }
2300 
updateUniformBufferCache(const gl::Caps & caps)2301 void ProgramD3D::updateUniformBufferCache(const gl::Caps &caps)
2302 {
2303     if (mState.getUniformBlocks().empty())
2304     {
2305         return;
2306     }
2307 
2308     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2309     {
2310         mShaderUBOCaches[shaderType].clear();
2311         mShaderUBOCachesUseSB[shaderType].clear();
2312     }
2313 
2314     for (unsigned int uniformBlockIndex = 0; uniformBlockIndex < mD3DUniformBlocks.size();
2315          uniformBlockIndex++)
2316     {
2317         const D3DUniformBlock &uniformBlock = mD3DUniformBlocks[uniformBlockIndex];
2318         GLuint blockBinding                 = mState.getUniformBlockBinding(uniformBlockIndex);
2319 
2320         // Unnecessary to apply an unreferenced standard or shared UBO
2321         for (gl::ShaderType shaderType : gl::AllShaderTypes())
2322         {
2323             if (!uniformBlock.activeInShader(shaderType))
2324             {
2325                 continue;
2326             }
2327 
2328             bool useStructuredBuffer   = uniformBlock.mUseStructuredBuffers[shaderType];
2329             unsigned int registerIndex = uniformBlock.mShaderRegisterIndexes[shaderType];
2330             if (useStructuredBuffer)
2331             {
2332                 D3DUBOCacheUseSB cacheUseSB;
2333                 cacheUseSB.registerIndex       = registerIndex;
2334                 cacheUseSB.binding             = blockBinding;
2335                 cacheUseSB.byteWidth           = uniformBlock.mByteWidths[shaderType];
2336                 cacheUseSB.structureByteStride = uniformBlock.mStructureByteStrides[shaderType];
2337                 mShaderUBOCachesUseSB[shaderType].push_back(cacheUseSB);
2338             }
2339             else
2340             {
2341                 ASSERT(registerIndex <
2342                        static_cast<unsigned int>(caps.maxShaderUniformBlocks[shaderType]));
2343                 D3DUBOCache cache;
2344                 cache.registerIndex = registerIndex;
2345                 cache.binding       = blockBinding;
2346                 mShaderUBOCaches[shaderType].push_back(cache);
2347             }
2348         }
2349     }
2350 
2351     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2352     {
2353         GLuint uniformBlockCount = static_cast<GLuint>(mShaderUBOCaches[shaderType].size() +
2354                                                        mShaderUBOCachesUseSB[shaderType].size());
2355         ASSERT(uniformBlockCount <=
2356                static_cast<unsigned int>(caps.maxShaderUniformBlocks[shaderType]));
2357     }
2358 }
2359 
getAtomicCounterBufferRegisterIndex(GLuint binding,gl::ShaderType shaderType) const2360 unsigned int ProgramD3D::getAtomicCounterBufferRegisterIndex(GLuint binding,
2361                                                              gl::ShaderType shaderType) const
2362 {
2363     if (shaderType != gl::ShaderType::Compute)
2364     {
2365         // Implement atomic counters for non-compute shaders
2366         // http://anglebug.com/1729
2367         UNIMPLEMENTED();
2368     }
2369     return mComputeAtomicCounterBufferRegisterIndices[binding];
2370 }
2371 
getShaderStorageBufferRegisterIndex(GLuint blockIndex,gl::ShaderType shaderType) const2372 unsigned int ProgramD3D::getShaderStorageBufferRegisterIndex(GLuint blockIndex,
2373                                                              gl::ShaderType shaderType) const
2374 {
2375     return mD3DShaderStorageBlocks[blockIndex].mShaderRegisterIndexes[shaderType];
2376 }
2377 
getShaderUniformBufferCache(gl::ShaderType shaderType) const2378 const std::vector<D3DUBOCache> &ProgramD3D::getShaderUniformBufferCache(
2379     gl::ShaderType shaderType) const
2380 {
2381     return mShaderUBOCaches[shaderType];
2382 }
2383 
getShaderUniformBufferCacheUseSB(gl::ShaderType shaderType) const2384 const std::vector<D3DUBOCacheUseSB> &ProgramD3D::getShaderUniformBufferCacheUseSB(
2385     gl::ShaderType shaderType) const
2386 {
2387     return mShaderUBOCachesUseSB[shaderType];
2388 }
2389 
dirtyAllUniforms()2390 void ProgramD3D::dirtyAllUniforms()
2391 {
2392     mShaderUniformsDirty = mState.getExecutable().getLinkedShaderStages();
2393 }
2394 
markUniformsClean()2395 void ProgramD3D::markUniformsClean()
2396 {
2397     mShaderUniformsDirty.reset();
2398 }
2399 
setUniform1fv(GLint location,GLsizei count,const GLfloat * v)2400 void ProgramD3D::setUniform1fv(GLint location, GLsizei count, const GLfloat *v)
2401 {
2402     setUniformInternal(location, count, v, GL_FLOAT);
2403 }
2404 
setUniform2fv(GLint location,GLsizei count,const GLfloat * v)2405 void ProgramD3D::setUniform2fv(GLint location, GLsizei count, const GLfloat *v)
2406 {
2407     setUniformInternal(location, count, v, GL_FLOAT_VEC2);
2408 }
2409 
setUniform3fv(GLint location,GLsizei count,const GLfloat * v)2410 void ProgramD3D::setUniform3fv(GLint location, GLsizei count, const GLfloat *v)
2411 {
2412     setUniformInternal(location, count, v, GL_FLOAT_VEC3);
2413 }
2414 
setUniform4fv(GLint location,GLsizei count,const GLfloat * v)2415 void ProgramD3D::setUniform4fv(GLint location, GLsizei count, const GLfloat *v)
2416 {
2417     setUniformInternal(location, count, v, GL_FLOAT_VEC4);
2418 }
2419 
setUniformMatrix2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2420 void ProgramD3D::setUniformMatrix2fv(GLint location,
2421                                      GLsizei count,
2422                                      GLboolean transpose,
2423                                      const GLfloat *value)
2424 {
2425     setUniformMatrixfvInternal<2, 2>(location, count, transpose, value);
2426 }
2427 
setUniformMatrix3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2428 void ProgramD3D::setUniformMatrix3fv(GLint location,
2429                                      GLsizei count,
2430                                      GLboolean transpose,
2431                                      const GLfloat *value)
2432 {
2433     setUniformMatrixfvInternal<3, 3>(location, count, transpose, value);
2434 }
2435 
setUniformMatrix4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2436 void ProgramD3D::setUniformMatrix4fv(GLint location,
2437                                      GLsizei count,
2438                                      GLboolean transpose,
2439                                      const GLfloat *value)
2440 {
2441     setUniformMatrixfvInternal<4, 4>(location, count, transpose, value);
2442 }
2443 
setUniformMatrix2x3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2444 void ProgramD3D::setUniformMatrix2x3fv(GLint location,
2445                                        GLsizei count,
2446                                        GLboolean transpose,
2447                                        const GLfloat *value)
2448 {
2449     setUniformMatrixfvInternal<2, 3>(location, count, transpose, value);
2450 }
2451 
setUniformMatrix3x2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2452 void ProgramD3D::setUniformMatrix3x2fv(GLint location,
2453                                        GLsizei count,
2454                                        GLboolean transpose,
2455                                        const GLfloat *value)
2456 {
2457     setUniformMatrixfvInternal<3, 2>(location, count, transpose, value);
2458 }
2459 
setUniformMatrix2x4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2460 void ProgramD3D::setUniformMatrix2x4fv(GLint location,
2461                                        GLsizei count,
2462                                        GLboolean transpose,
2463                                        const GLfloat *value)
2464 {
2465     setUniformMatrixfvInternal<2, 4>(location, count, transpose, value);
2466 }
2467 
setUniformMatrix4x2fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2468 void ProgramD3D::setUniformMatrix4x2fv(GLint location,
2469                                        GLsizei count,
2470                                        GLboolean transpose,
2471                                        const GLfloat *value)
2472 {
2473     setUniformMatrixfvInternal<4, 2>(location, count, transpose, value);
2474 }
2475 
setUniformMatrix3x4fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2476 void ProgramD3D::setUniformMatrix3x4fv(GLint location,
2477                                        GLsizei count,
2478                                        GLboolean transpose,
2479                                        const GLfloat *value)
2480 {
2481     setUniformMatrixfvInternal<3, 4>(location, count, transpose, value);
2482 }
2483 
setUniformMatrix4x3fv(GLint location,GLsizei count,GLboolean transpose,const GLfloat * value)2484 void ProgramD3D::setUniformMatrix4x3fv(GLint location,
2485                                        GLsizei count,
2486                                        GLboolean transpose,
2487                                        const GLfloat *value)
2488 {
2489     setUniformMatrixfvInternal<4, 3>(location, count, transpose, value);
2490 }
2491 
setUniform1iv(GLint location,GLsizei count,const GLint * v)2492 void ProgramD3D::setUniform1iv(GLint location, GLsizei count, const GLint *v)
2493 {
2494     setUniformInternal(location, count, v, GL_INT);
2495 }
2496 
setUniform2iv(GLint location,GLsizei count,const GLint * v)2497 void ProgramD3D::setUniform2iv(GLint location, GLsizei count, const GLint *v)
2498 {
2499     setUniformInternal(location, count, v, GL_INT_VEC2);
2500 }
2501 
setUniform3iv(GLint location,GLsizei count,const GLint * v)2502 void ProgramD3D::setUniform3iv(GLint location, GLsizei count, const GLint *v)
2503 {
2504     setUniformInternal(location, count, v, GL_INT_VEC3);
2505 }
2506 
setUniform4iv(GLint location,GLsizei count,const GLint * v)2507 void ProgramD3D::setUniform4iv(GLint location, GLsizei count, const GLint *v)
2508 {
2509     setUniformInternal(location, count, v, GL_INT_VEC4);
2510 }
2511 
setUniform1uiv(GLint location,GLsizei count,const GLuint * v)2512 void ProgramD3D::setUniform1uiv(GLint location, GLsizei count, const GLuint *v)
2513 {
2514     setUniformInternal(location, count, v, GL_UNSIGNED_INT);
2515 }
2516 
setUniform2uiv(GLint location,GLsizei count,const GLuint * v)2517 void ProgramD3D::setUniform2uiv(GLint location, GLsizei count, const GLuint *v)
2518 {
2519     setUniformInternal(location, count, v, GL_UNSIGNED_INT_VEC2);
2520 }
2521 
setUniform3uiv(GLint location,GLsizei count,const GLuint * v)2522 void ProgramD3D::setUniform3uiv(GLint location, GLsizei count, const GLuint *v)
2523 {
2524     setUniformInternal(location, count, v, GL_UNSIGNED_INT_VEC3);
2525 }
2526 
setUniform4uiv(GLint location,GLsizei count,const GLuint * v)2527 void ProgramD3D::setUniform4uiv(GLint location, GLsizei count, const GLuint *v)
2528 {
2529     setUniformInternal(location, count, v, GL_UNSIGNED_INT_VEC4);
2530 }
2531 
defineUniformsAndAssignRegisters()2532 void ProgramD3D::defineUniformsAndAssignRegisters()
2533 {
2534     D3DUniformMap uniformMap;
2535 
2536     gl::ShaderBitSet attachedShaders;
2537     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2538     {
2539         gl::Shader *shader = mState.getAttachedShader(shaderType);
2540         if (shader)
2541         {
2542             for (const sh::ShaderVariable &uniform : shader->getUniforms())
2543             {
2544                 if (uniform.active)
2545                 {
2546                     defineUniformBase(shader, uniform, &uniformMap);
2547                 }
2548             }
2549 
2550             attachedShaders.set(shader->getType());
2551         }
2552     }
2553 
2554     // Initialize the D3DUniform list to mirror the indexing of the GL layer.
2555     for (const gl::LinkedUniform &glUniform : mState.getUniforms())
2556     {
2557         if (!glUniform.isInDefaultBlock())
2558             continue;
2559 
2560         std::string name = glUniform.name;
2561         if (glUniform.isArray())
2562         {
2563             // In the program state, array uniform names include [0] as in the program resource
2564             // spec. Here we don't include it.
2565             // TODO(oetuaho@nvidia.com): consider using the same uniform naming here as in the GL
2566             // layer.
2567             ASSERT(angle::EndsWith(name, "[0]"));
2568             name.resize(name.length() - 3);
2569         }
2570         auto mapEntry = uniformMap.find(name);
2571         ASSERT(mapEntry != uniformMap.end());
2572         mD3DUniforms.push_back(mapEntry->second);
2573     }
2574 
2575     assignAllSamplerRegisters();
2576     assignAllAtomicCounterRegisters();
2577     // Samplers and readonly images share shader input resource slot, adjust low value of
2578     // readonly image range.
2579     mUsedComputeReadonlyImageRange =
2580         gl::RangeUI(mUsedShaderSamplerRanges[gl::ShaderType::Compute].high(),
2581                     mUsedShaderSamplerRanges[gl::ShaderType::Compute].high());
2582     // Atomic counter buffers and non-readonly images share input resource slots
2583     mUsedComputeImageRange =
2584         gl::RangeUI(mUsedComputeAtomicCounterRange.high(), mUsedComputeAtomicCounterRange.high());
2585     assignAllImageRegisters();
2586     initializeUniformStorage(attachedShaders);
2587 }
2588 
defineUniformBase(const gl::Shader * shader,const sh::ShaderVariable & uniform,D3DUniformMap * uniformMap)2589 void ProgramD3D::defineUniformBase(const gl::Shader *shader,
2590                                    const sh::ShaderVariable &uniform,
2591                                    D3DUniformMap *uniformMap)
2592 {
2593     sh::StubBlockEncoder stubEncoder;
2594 
2595     // Samplers get their registers assigned in assignAllSamplerRegisters, and images get their
2596     // registers assigned in assignAllImageRegisters.
2597     if (gl::IsSamplerType(uniform.type))
2598     {
2599         UniformEncodingVisitorD3D visitor(shader->getType(), HLSLRegisterType::Texture,
2600                                           &stubEncoder, uniformMap);
2601         sh::TraverseShaderVariable(uniform, false, &visitor);
2602         return;
2603     }
2604 
2605     if (gl::IsImageType(uniform.type))
2606     {
2607         if (uniform.readonly)
2608         {
2609             UniformEncodingVisitorD3D visitor(shader->getType(), HLSLRegisterType::Texture,
2610                                               &stubEncoder, uniformMap);
2611             sh::TraverseShaderVariable(uniform, false, &visitor);
2612         }
2613         else
2614         {
2615             UniformEncodingVisitorD3D visitor(
2616                 shader->getType(), HLSLRegisterType::UnorderedAccessView, &stubEncoder, uniformMap);
2617             sh::TraverseShaderVariable(uniform, false, &visitor);
2618         }
2619         mImageBindingMap[uniform.name] = uniform.binding;
2620         return;
2621     }
2622 
2623     if (uniform.isBuiltIn() && !uniform.isEmulatedBuiltIn())
2624     {
2625         UniformEncodingVisitorD3D visitor(shader->getType(), HLSLRegisterType::None, &stubEncoder,
2626                                           uniformMap);
2627         sh::TraverseShaderVariable(uniform, false, &visitor);
2628         return;
2629     }
2630     else if (gl::IsAtomicCounterType(uniform.type))
2631     {
2632         UniformEncodingVisitorD3D visitor(shader->getType(), HLSLRegisterType::UnorderedAccessView,
2633                                           &stubEncoder, uniformMap);
2634         sh::TraverseShaderVariable(uniform, false, &visitor);
2635         mAtomicBindingMap[uniform.name] = uniform.binding;
2636         return;
2637     }
2638 
2639     const ShaderD3D *shaderD3D = GetImplAs<ShaderD3D>(shader);
2640     unsigned int startRegister = shaderD3D->getUniformRegister(uniform.name);
2641     ShShaderOutput outputType  = shaderD3D->getCompilerOutputType();
2642     sh::HLSLBlockEncoder encoder(sh::HLSLBlockEncoder::GetStrategyFor(outputType), true);
2643     encoder.skipRegisters(startRegister);
2644 
2645     UniformEncodingVisitorD3D visitor(shader->getType(), HLSLRegisterType::None, &encoder,
2646                                       uniformMap);
2647     sh::TraverseShaderVariable(uniform, false, &visitor);
2648 }
2649 
hasNamedUniform(const std::string & name)2650 bool ProgramD3D::hasNamedUniform(const std::string &name)
2651 {
2652     for (D3DUniform *d3dUniform : mD3DUniforms)
2653     {
2654         if (d3dUniform->name == name)
2655         {
2656             return true;
2657         }
2658     }
2659 
2660     return false;
2661 }
2662 
2663 // Assume count is already clamped.
2664 template <typename T>
setUniformImpl(D3DUniform * targetUniform,const gl::VariableLocation & locationInfo,GLsizei count,const T * v,uint8_t * targetState,GLenum uniformType)2665 void ProgramD3D::setUniformImpl(D3DUniform *targetUniform,
2666                                 const gl::VariableLocation &locationInfo,
2667                                 GLsizei count,
2668                                 const T *v,
2669                                 uint8_t *targetState,
2670                                 GLenum uniformType)
2671 {
2672     const int components                  = targetUniform->typeInfo.componentCount;
2673     const unsigned int arrayElementOffset = locationInfo.arrayIndex;
2674     const int blockSize                   = 4;
2675 
2676     if (targetUniform->typeInfo.type == uniformType)
2677     {
2678         T *dest         = reinterpret_cast<T *>(targetState) + arrayElementOffset * blockSize;
2679         const T *source = v;
2680 
2681         // If the component is equal to the block size, we can optimize to a single memcpy.
2682         // Otherwise, we have to do partial block writes.
2683         if (components == blockSize)
2684         {
2685             memcpy(dest, source, components * count * sizeof(T));
2686         }
2687         else
2688         {
2689             for (GLint i = 0; i < count; i++, dest += blockSize, source += components)
2690             {
2691                 memcpy(dest, source, components * sizeof(T));
2692             }
2693         }
2694     }
2695     else
2696     {
2697         ASSERT(targetUniform->typeInfo.type == gl::VariableBoolVectorType(uniformType));
2698         GLint *boolParams = reinterpret_cast<GLint *>(targetState) + arrayElementOffset * 4;
2699 
2700         for (GLint i = 0; i < count; i++)
2701         {
2702             GLint *dest     = boolParams + (i * 4);
2703             const T *source = v + (i * components);
2704 
2705             for (int c = 0; c < components; c++)
2706             {
2707                 dest[c] = (source[c] == static_cast<T>(0)) ? GL_FALSE : GL_TRUE;
2708             }
2709         }
2710     }
2711 }
2712 
2713 template <typename T>
setUniformInternal(GLint location,GLsizei count,const T * v,GLenum uniformType)2714 void ProgramD3D::setUniformInternal(GLint location, GLsizei count, const T *v, GLenum uniformType)
2715 {
2716     const gl::VariableLocation &locationInfo = mState.getUniformLocations()[location];
2717     D3DUniform *targetUniform                = mD3DUniforms[locationInfo.index];
2718 
2719     if (targetUniform->typeInfo.isSampler)
2720     {
2721         ASSERT(uniformType == GL_INT);
2722         size_t size = count * sizeof(T);
2723         GLint *dest = &targetUniform->mSamplerData[locationInfo.arrayIndex];
2724         if (memcmp(dest, v, size) != 0)
2725         {
2726             memcpy(dest, v, size);
2727             mDirtySamplerMapping = true;
2728         }
2729         return;
2730     }
2731 
2732     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2733     {
2734         uint8_t *targetState = targetUniform->mShaderData[shaderType];
2735         if (targetState)
2736         {
2737             setUniformImpl(targetUniform, locationInfo, count, v, targetState, uniformType);
2738             mShaderUniformsDirty.set(shaderType);
2739         }
2740     }
2741 }
2742 
2743 template <int cols, int rows>
setUniformMatrixfvInternal(GLint location,GLsizei countIn,GLboolean transpose,const GLfloat * value)2744 void ProgramD3D::setUniformMatrixfvInternal(GLint location,
2745                                             GLsizei countIn,
2746                                             GLboolean transpose,
2747                                             const GLfloat *value)
2748 {
2749     D3DUniform *targetUniform                   = getD3DUniformFromLocation(location);
2750     const gl::VariableLocation &uniformLocation = mState.getUniformLocations()[location];
2751     unsigned int arrayElementOffset             = uniformLocation.arrayIndex;
2752     unsigned int elementCount                   = targetUniform->getArraySizeProduct();
2753 
2754     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2755     {
2756         if (targetUniform->mShaderData[shaderType])
2757         {
2758             SetFloatUniformMatrixHLSL<cols, rows>::Run(arrayElementOffset, elementCount, countIn,
2759                                                        transpose, value,
2760                                                        targetUniform->mShaderData[shaderType]);
2761             mShaderUniformsDirty.set(shaderType);
2762         }
2763     }
2764 }
2765 
assignAllSamplerRegisters()2766 void ProgramD3D::assignAllSamplerRegisters()
2767 {
2768     for (size_t uniformIndex = 0; uniformIndex < mD3DUniforms.size(); ++uniformIndex)
2769     {
2770         if (mD3DUniforms[uniformIndex]->isSampler())
2771         {
2772             assignSamplerRegisters(uniformIndex);
2773         }
2774     }
2775 }
2776 
assignSamplerRegisters(size_t uniformIndex)2777 void ProgramD3D::assignSamplerRegisters(size_t uniformIndex)
2778 {
2779     D3DUniform *d3dUniform = mD3DUniforms[uniformIndex];
2780     ASSERT(d3dUniform->isSampler());
2781     // If the uniform is an array of arrays, then we have separate entries for each inner array in
2782     // mD3DUniforms. However, the sampler register info is stored in the shader only for the
2783     // outermost array.
2784     std::vector<unsigned int> subscripts;
2785     const std::string baseName = gl::ParseResourceName(d3dUniform->name, &subscripts);
2786     unsigned int registerOffset =
2787         mState.getUniforms()[uniformIndex].parentArrayIndex() * d3dUniform->getArraySizeProduct();
2788 
2789     bool hasUniform = false;
2790     for (gl::ShaderType shaderType : gl::AllShaderTypes())
2791     {
2792         if (!mState.getAttachedShader(shaderType))
2793         {
2794             continue;
2795         }
2796 
2797         const ShaderD3D *shaderD3D = GetImplAs<ShaderD3D>(mState.getAttachedShader(shaderType));
2798         if (shaderD3D->hasUniform(baseName))
2799         {
2800             d3dUniform->mShaderRegisterIndexes[shaderType] =
2801                 shaderD3D->getUniformRegister(baseName) + registerOffset;
2802             ASSERT(d3dUniform->mShaderRegisterIndexes[shaderType] != GL_INVALID_VALUE);
2803 
2804             AssignSamplers(d3dUniform->mShaderRegisterIndexes[shaderType], d3dUniform->typeInfo,
2805                            d3dUniform->getArraySizeProduct(), mShaderSamplers[shaderType],
2806                            &mUsedShaderSamplerRanges[shaderType]);
2807             hasUniform = true;
2808         }
2809     }
2810 
2811     ASSERT(hasUniform);
2812 }
2813 
2814 // static
AssignSamplers(unsigned int startSamplerIndex,const gl::UniformTypeInfo & typeInfo,unsigned int samplerCount,std::vector<Sampler> & outSamplers,gl::RangeUI * outUsedRange)2815 void ProgramD3D::AssignSamplers(unsigned int startSamplerIndex,
2816                                 const gl::UniformTypeInfo &typeInfo,
2817                                 unsigned int samplerCount,
2818                                 std::vector<Sampler> &outSamplers,
2819                                 gl::RangeUI *outUsedRange)
2820 {
2821     unsigned int samplerIndex = startSamplerIndex;
2822     unsigned int low          = outUsedRange->low();
2823     unsigned int high         = outUsedRange->high();
2824 
2825     do
2826     {
2827         ASSERT(samplerIndex < outSamplers.size());
2828         Sampler *sampler            = &outSamplers[samplerIndex];
2829         sampler->active             = true;
2830         sampler->textureType        = gl::FromGLenum<gl::TextureType>(typeInfo.textureType);
2831         sampler->logicalTextureUnit = 0;
2832         low                         = std::min(samplerIndex, low);
2833         high                        = std::max(samplerIndex + 1, high);
2834         samplerIndex++;
2835     } while (samplerIndex < startSamplerIndex + samplerCount);
2836 
2837     ASSERT(low < high);
2838     *outUsedRange = gl::RangeUI(low, high);
2839 }
2840 
assignAllImageRegisters()2841 void ProgramD3D::assignAllImageRegisters()
2842 {
2843     for (size_t uniformIndex = 0; uniformIndex < mD3DUniforms.size(); ++uniformIndex)
2844     {
2845         if (mD3DUniforms[uniformIndex]->isImage() && !mD3DUniforms[uniformIndex]->isImage2D())
2846         {
2847             assignImageRegisters(uniformIndex);
2848         }
2849     }
2850 }
2851 
assignAllAtomicCounterRegisters()2852 void ProgramD3D::assignAllAtomicCounterRegisters()
2853 {
2854     if (mAtomicBindingMap.empty())
2855     {
2856         return;
2857     }
2858     gl::ShaderType shaderType       = gl::ShaderType::Compute;
2859     const gl::Shader *computeShader = mState.getAttachedShader(shaderType);
2860     if (computeShader)
2861     {
2862         const ShaderD3D *computeShaderD3D = GetImplAs<ShaderD3D>(computeShader);
2863         auto &registerIndices             = mComputeAtomicCounterBufferRegisterIndices;
2864         unsigned int firstRegister        = GL_INVALID_VALUE;
2865         unsigned int lastRegister         = 0;
2866         for (auto &atomicBinding : mAtomicBindingMap)
2867         {
2868             ASSERT(computeShaderD3D->hasUniform(atomicBinding.first));
2869             unsigned int currentRegister =
2870                 computeShaderD3D->getUniformRegister(atomicBinding.first);
2871             ASSERT(currentRegister != GL_INVALID_INDEX);
2872             const int kBinding = atomicBinding.second;
2873 
2874             registerIndices[kBinding] = currentRegister;
2875 
2876             firstRegister = std::min(firstRegister, currentRegister);
2877             lastRegister  = std::max(lastRegister, currentRegister);
2878         }
2879         ASSERT(firstRegister != GL_INVALID_VALUE);
2880         ASSERT(lastRegister != GL_INVALID_VALUE);
2881         mUsedComputeAtomicCounterRange = gl::RangeUI(firstRegister, lastRegister + 1);
2882     }
2883     else
2884     {
2885         // Implement atomic counters for non-compute shaders
2886         // http://anglebug.com/1729
2887         UNIMPLEMENTED();
2888     }
2889 }
2890 
assignImageRegisters(size_t uniformIndex)2891 void ProgramD3D::assignImageRegisters(size_t uniformIndex)
2892 {
2893     D3DUniform *d3dUniform = mD3DUniforms[uniformIndex];
2894     ASSERT(d3dUniform->isImage());
2895     // If the uniform is an array of arrays, then we have separate entries for each inner array in
2896     // mD3DUniforms. However, the image register info is stored in the shader only for the
2897     // outermost array.
2898     std::vector<unsigned int> subscripts;
2899     const std::string baseName = gl::ParseResourceName(d3dUniform->name, &subscripts);
2900     unsigned int registerOffset =
2901         mState.getUniforms()[uniformIndex].parentArrayIndex() * d3dUniform->getArraySizeProduct();
2902 
2903     const gl::Shader *computeShader = mState.getAttachedShader(gl::ShaderType::Compute);
2904     if (computeShader)
2905     {
2906         const ShaderD3D *computeShaderD3D =
2907             GetImplAs<ShaderD3D>(mState.getAttachedShader(gl::ShaderType::Compute));
2908         ASSERT(computeShaderD3D->hasUniform(baseName));
2909         d3dUniform->mShaderRegisterIndexes[gl::ShaderType::Compute] =
2910             computeShaderD3D->getUniformRegister(baseName) + registerOffset;
2911         ASSERT(d3dUniform->mShaderRegisterIndexes[gl::ShaderType::Compute] != GL_INVALID_INDEX);
2912         auto bindingIter = mImageBindingMap.find(baseName);
2913         ASSERT(bindingIter != mImageBindingMap.end());
2914         if (d3dUniform->regType == HLSLRegisterType::Texture)
2915         {
2916             AssignImages(d3dUniform->mShaderRegisterIndexes[gl::ShaderType::Compute],
2917                          bindingIter->second, d3dUniform->getArraySizeProduct(), mReadonlyImagesCS,
2918                          &mUsedComputeReadonlyImageRange);
2919         }
2920         else if (d3dUniform->regType == HLSLRegisterType::UnorderedAccessView)
2921         {
2922             AssignImages(d3dUniform->mShaderRegisterIndexes[gl::ShaderType::Compute],
2923                          bindingIter->second, d3dUniform->getArraySizeProduct(), mImagesCS,
2924                          &mUsedComputeImageRange);
2925         }
2926         else
2927         {
2928             UNREACHABLE();
2929         }
2930     }
2931     else
2932     {
2933         // TODO(xinghua.cao@intel.com): Implement image variables in vertex shader and pixel shader.
2934         UNIMPLEMENTED();
2935     }
2936 }
2937 
2938 // static
AssignImages(unsigned int startImageIndex,int startLogicalImageUnit,unsigned int imageCount,std::vector<Image> & outImages,gl::RangeUI * outUsedRange)2939 void ProgramD3D::AssignImages(unsigned int startImageIndex,
2940                               int startLogicalImageUnit,
2941                               unsigned int imageCount,
2942                               std::vector<Image> &outImages,
2943                               gl::RangeUI *outUsedRange)
2944 {
2945     unsigned int imageIndex = startImageIndex;
2946     unsigned int low        = outUsedRange->low();
2947     unsigned int high       = outUsedRange->high();
2948 
2949     // If declare without a binding qualifier, any uniform image variable (include all elements of
2950     // unbound image array) shoud be bound to unit zero.
2951     if (startLogicalImageUnit == -1)
2952     {
2953         ASSERT(imageIndex < outImages.size());
2954         Image *image            = &outImages[imageIndex];
2955         image->active           = true;
2956         image->logicalImageUnit = 0;
2957         low                     = std::min(imageIndex, low);
2958         high                    = std::max(imageIndex + 1, high);
2959         ASSERT(low < high);
2960         *outUsedRange = gl::RangeUI(low, high);
2961         return;
2962     }
2963 
2964     unsigned int logcalImageUnit = startLogicalImageUnit;
2965     do
2966     {
2967         ASSERT(imageIndex < outImages.size());
2968         Image *image            = &outImages[imageIndex];
2969         image->active           = true;
2970         image->logicalImageUnit = logcalImageUnit;
2971         low                     = std::min(imageIndex, low);
2972         high                    = std::max(imageIndex + 1, high);
2973         imageIndex++;
2974         logcalImageUnit++;
2975     } while (imageIndex < startImageIndex + imageCount);
2976 
2977     ASSERT(low < high);
2978     *outUsedRange = gl::RangeUI(low, high);
2979 }
2980 
assignImage2DRegisters(unsigned int startImageIndex,int startLogicalImageUnit,bool readonly)2981 void ProgramD3D::assignImage2DRegisters(unsigned int startImageIndex,
2982                                         int startLogicalImageUnit,
2983                                         bool readonly)
2984 {
2985     if (readonly)
2986     {
2987         AssignImages(startImageIndex, startLogicalImageUnit, 1, mReadonlyImagesCS,
2988                      &mUsedComputeReadonlyImageRange);
2989     }
2990     else
2991     {
2992         AssignImages(startImageIndex, startLogicalImageUnit, 1, mImagesCS, &mUsedComputeImageRange);
2993     }
2994 }
2995 
reset()2996 void ProgramD3D::reset()
2997 {
2998     mVertexExecutables.clear();
2999     mPixelExecutables.clear();
3000     mComputeExecutables.clear();
3001 
3002     for (auto &geometryExecutable : mGeometryExecutables)
3003     {
3004         geometryExecutable.reset(nullptr);
3005     }
3006 
3007     for (gl::ShaderType shaderType : gl::AllShaderTypes())
3008     {
3009         mShaderHLSL[shaderType].clear();
3010     }
3011 
3012     mUsesFragDepth            = false;
3013     mHasANGLEMultiviewEnabled = false;
3014     mUsesVertexID             = false;
3015     mUsesViewID               = false;
3016     mPixelShaderKey.clear();
3017     mUsesPointSize         = false;
3018     mUsesFlatInterpolation = false;
3019 
3020     SafeDeleteContainer(mD3DUniforms);
3021     mD3DUniformBlocks.clear();
3022     mD3DShaderStorageBlocks.clear();
3023     mComputeAtomicCounterBufferRegisterIndices.fill({});
3024 
3025     for (gl::ShaderType shaderType : gl::AllShaderTypes())
3026     {
3027         mShaderUniformStorages[shaderType].reset();
3028         mShaderSamplers[shaderType].clear();
3029     }
3030 
3031     mImagesCS.clear();
3032     mReadonlyImagesCS.clear();
3033 
3034     mUsedShaderSamplerRanges.fill({0, 0});
3035     mUsedComputeAtomicCounterRange = {0, 0};
3036     mDirtySamplerMapping           = true;
3037     mUsedComputeImageRange         = {0, 0};
3038     mUsedComputeReadonlyImageRange = {0, 0};
3039 
3040     mAttribLocationToD3DSemantic.fill(-1);
3041 
3042     mStreamOutVaryings.clear();
3043 
3044     mGeometryShaderPreamble.clear();
3045 
3046     markUniformsClean();
3047 
3048     mCachedPixelExecutableIndex.reset();
3049     mCachedVertexExecutableIndex.reset();
3050 }
3051 
getSerial() const3052 unsigned int ProgramD3D::getSerial() const
3053 {
3054     return mSerial;
3055 }
3056 
issueSerial()3057 unsigned int ProgramD3D::issueSerial()
3058 {
3059     return mCurrentSerial++;
3060 }
3061 
initAttribLocationsToD3DSemantic()3062 void ProgramD3D::initAttribLocationsToD3DSemantic()
3063 {
3064     gl::Shader *vertexShader = mState.getAttachedShader(gl::ShaderType::Vertex);
3065     if (!vertexShader)
3066     {
3067         return;
3068     }
3069 
3070     // Init semantic index
3071     int semanticIndex = 0;
3072     for (const sh::ShaderVariable &attribute : vertexShader->getActiveAttributes())
3073     {
3074         int regCount    = gl::VariableRegisterCount(attribute.type);
3075         GLuint location = mState.getAttributeLocation(attribute.name);
3076         ASSERT(location != std::numeric_limits<GLuint>::max());
3077 
3078         for (int reg = 0; reg < regCount; ++reg)
3079         {
3080             mAttribLocationToD3DSemantic[location + reg] = semanticIndex++;
3081         }
3082     }
3083 }
3084 
updateCachedInputLayout(Serial associatedSerial,const gl::State & state)3085 void ProgramD3D::updateCachedInputLayout(Serial associatedSerial, const gl::State &state)
3086 {
3087     if (mCurrentVertexArrayStateSerial == associatedSerial)
3088     {
3089         return;
3090     }
3091 
3092     mCurrentVertexArrayStateSerial = associatedSerial;
3093     mCachedInputLayout.clear();
3094 
3095     const auto &vertexAttributes = state.getVertexArray()->getVertexAttributes();
3096     const gl::AttributesMask &attributesMask =
3097         mState.getExecutable().getActiveAttribLocationsMask();
3098 
3099     for (size_t locationIndex : attributesMask)
3100     {
3101         int d3dSemantic = mAttribLocationToD3DSemantic[locationIndex];
3102 
3103         if (d3dSemantic != -1)
3104         {
3105             if (mCachedInputLayout.size() < static_cast<size_t>(d3dSemantic + 1))
3106             {
3107                 mCachedInputLayout.resize(d3dSemantic + 1, angle::FormatID::NONE);
3108             }
3109             mCachedInputLayout[d3dSemantic] =
3110                 GetVertexFormatID(vertexAttributes[locationIndex],
3111                                   state.getVertexAttribCurrentValue(locationIndex).Type);
3112         }
3113     }
3114 
3115     VertexExecutable::getSignature(mRenderer, mCachedInputLayout, &mCachedVertexSignature);
3116 
3117     updateCachedVertexExecutableIndex();
3118 }
3119 
updateCachedOutputLayout(const gl::Context * context,const gl::Framebuffer * framebuffer)3120 void ProgramD3D::updateCachedOutputLayout(const gl::Context *context,
3121                                           const gl::Framebuffer *framebuffer)
3122 {
3123     mPixelShaderOutputLayoutCache.clear();
3124 
3125     FramebufferD3D *fboD3D   = GetImplAs<FramebufferD3D>(framebuffer);
3126     const auto &colorbuffers = fboD3D->getColorAttachmentsForRender(context);
3127 
3128     for (size_t colorAttachment = 0; colorAttachment < colorbuffers.size(); ++colorAttachment)
3129     {
3130         const gl::FramebufferAttachment *colorbuffer = colorbuffers[colorAttachment];
3131 
3132         if (colorbuffer)
3133         {
3134             auto binding = colorbuffer->getBinding() == GL_BACK ? GL_COLOR_ATTACHMENT0
3135                                                                 : colorbuffer->getBinding();
3136             size_t maxIndex = binding != GL_NONE ? GetMaxOutputIndex(mPixelShaderKey,
3137                                                                      binding - GL_COLOR_ATTACHMENT0)
3138                                                  : 0;
3139             mPixelShaderOutputLayoutCache.insert(mPixelShaderOutputLayoutCache.end(), maxIndex + 1,
3140                                                  binding);
3141         }
3142         else
3143         {
3144             mPixelShaderOutputLayoutCache.push_back(GL_NONE);
3145         }
3146     }
3147 
3148     updateCachedPixelExecutableIndex();
3149 }
3150 
updateCachedComputeImage2DBindLayout(const gl::Context * context)3151 void ProgramD3D::updateCachedComputeImage2DBindLayout(const gl::Context *context)
3152 {
3153     const auto &glState = context->getState();
3154     for (auto &image2DBindLayout : mComputeShaderImage2DBindLayoutCache)
3155     {
3156         const gl::ImageUnit &imageUnit = glState.getImageUnit(image2DBindLayout.first);
3157         if (imageUnit.texture.get())
3158         {
3159             image2DBindLayout.second = imageUnit.texture->getType();
3160         }
3161         else
3162         {
3163             image2DBindLayout.second = gl::TextureType::_2D;
3164         }
3165     }
3166 
3167     updateCachedComputeExecutableIndex();
3168 }
3169 
gatherTransformFeedbackVaryings(const gl::VaryingPacking & varyingPacking,const BuiltinInfo & builtins)3170 void ProgramD3D::gatherTransformFeedbackVaryings(const gl::VaryingPacking &varyingPacking,
3171                                                  const BuiltinInfo &builtins)
3172 {
3173     const std::string &varyingSemantic =
3174         GetVaryingSemantic(mRenderer->getMajorShaderModel(), usesPointSize());
3175 
3176     // Gather the linked varyings that are used for transform feedback, they should all exist.
3177     mStreamOutVaryings.clear();
3178 
3179     const auto &tfVaryingNames = mState.getTransformFeedbackVaryingNames();
3180     for (unsigned int outputSlot = 0; outputSlot < static_cast<unsigned int>(tfVaryingNames.size());
3181          ++outputSlot)
3182     {
3183         const auto &tfVaryingName = tfVaryingNames[outputSlot];
3184         if (tfVaryingName == "gl_Position")
3185         {
3186             if (builtins.glPosition.enabled)
3187             {
3188                 mStreamOutVaryings.emplace_back(builtins.glPosition.semantic,
3189                                                 builtins.glPosition.index, 4, outputSlot);
3190             }
3191         }
3192         else if (tfVaryingName == "gl_FragCoord")
3193         {
3194             if (builtins.glFragCoord.enabled)
3195             {
3196                 mStreamOutVaryings.emplace_back(builtins.glFragCoord.semantic,
3197                                                 builtins.glFragCoord.index, 4, outputSlot);
3198             }
3199         }
3200         else if (tfVaryingName == "gl_PointSize")
3201         {
3202             if (builtins.glPointSize.enabled)
3203             {
3204                 mStreamOutVaryings.emplace_back("PSIZE", 0, 1, outputSlot);
3205             }
3206         }
3207         else
3208         {
3209             const auto &registerInfos = varyingPacking.getRegisterList();
3210             for (GLuint registerIndex = 0u; registerIndex < registerInfos.size(); ++registerIndex)
3211             {
3212                 const auto &registerInfo = registerInfos[registerIndex];
3213                 const auto &varying      = registerInfo.packedVarying->varying();
3214                 GLenum transposedType    = gl::TransposeMatrixType(varying.type);
3215                 int componentCount       = gl::VariableColumnCount(transposedType);
3216                 ASSERT(!varying.isBuiltIn() && !varying.isStruct());
3217 
3218                 // There can be more than one register assigned to a particular varying, and each
3219                 // register needs its own stream out entry.
3220                 if (registerInfo.tfVaryingName() == tfVaryingName)
3221                 {
3222                     mStreamOutVaryings.emplace_back(varyingSemantic, registerIndex, componentCount,
3223                                                     outputSlot);
3224                 }
3225             }
3226         }
3227     }
3228 }
3229 
getD3DUniformFromLocation(GLint location)3230 D3DUniform *ProgramD3D::getD3DUniformFromLocation(GLint location)
3231 {
3232     return mD3DUniforms[mState.getUniformLocations()[location].index];
3233 }
3234 
getD3DUniformFromLocation(GLint location) const3235 const D3DUniform *ProgramD3D::getD3DUniformFromLocation(GLint location) const
3236 {
3237     return mD3DUniforms[mState.getUniformLocations()[location].index];
3238 }
3239 
hasVertexExecutableForCachedInputLayout()3240 bool ProgramD3D::hasVertexExecutableForCachedInputLayout()
3241 {
3242     return mCachedVertexExecutableIndex.valid();
3243 }
3244 
hasGeometryExecutableForPrimitiveType(const gl::State & state,gl::PrimitiveMode drawMode)3245 bool ProgramD3D::hasGeometryExecutableForPrimitiveType(const gl::State &state,
3246                                                        gl::PrimitiveMode drawMode)
3247 {
3248     if (!usesGeometryShader(state, drawMode))
3249     {
3250         // No shader necessary mean we have the required (null) executable.
3251         return true;
3252     }
3253 
3254     gl::PrimitiveMode geometryShaderType = GetGeometryShaderTypeFromDrawMode(drawMode);
3255     return mGeometryExecutables[geometryShaderType].get() != nullptr;
3256 }
3257 
hasPixelExecutableForCachedOutputLayout()3258 bool ProgramD3D::hasPixelExecutableForCachedOutputLayout()
3259 {
3260     return mCachedPixelExecutableIndex.valid();
3261 }
3262 
hasComputeExecutableForCachedImage2DBindLayout()3263 bool ProgramD3D::hasComputeExecutableForCachedImage2DBindLayout()
3264 {
3265     return mCachedComputeExecutableIndex.valid();
3266 }
3267 
3268 template <typename DestT>
getUniformInternal(GLint location,DestT * dataOut) const3269 void ProgramD3D::getUniformInternal(GLint location, DestT *dataOut) const
3270 {
3271     const gl::VariableLocation &locationInfo = mState.getUniformLocations()[location];
3272     const gl::LinkedUniform &uniform         = mState.getUniforms()[locationInfo.index];
3273 
3274     const D3DUniform *targetUniform = getD3DUniformFromLocation(location);
3275     const uint8_t *srcPointer       = targetUniform->getDataPtrToElement(locationInfo.arrayIndex);
3276 
3277     if (gl::IsMatrixType(uniform.type))
3278     {
3279         GetMatrixUniform(uniform.type, dataOut, reinterpret_cast<const DestT *>(srcPointer), true);
3280     }
3281     else
3282     {
3283         memcpy(dataOut, srcPointer, uniform.getElementSize());
3284     }
3285 }
3286 
getUniformfv(const gl::Context * context,GLint location,GLfloat * params) const3287 void ProgramD3D::getUniformfv(const gl::Context *context, GLint location, GLfloat *params) const
3288 {
3289     getUniformInternal(location, params);
3290 }
3291 
getUniformiv(const gl::Context * context,GLint location,GLint * params) const3292 void ProgramD3D::getUniformiv(const gl::Context *context, GLint location, GLint *params) const
3293 {
3294     getUniformInternal(location, params);
3295 }
3296 
getUniformuiv(const gl::Context * context,GLint location,GLuint * params) const3297 void ProgramD3D::getUniformuiv(const gl::Context *context, GLint location, GLuint *params) const
3298 {
3299     getUniformInternal(location, params);
3300 }
3301 
updateCachedVertexExecutableIndex()3302 void ProgramD3D::updateCachedVertexExecutableIndex()
3303 {
3304     mCachedVertexExecutableIndex.reset();
3305     for (size_t executableIndex = 0; executableIndex < mVertexExecutables.size(); executableIndex++)
3306     {
3307         if (mVertexExecutables[executableIndex]->matchesSignature(mCachedVertexSignature))
3308         {
3309             mCachedVertexExecutableIndex = executableIndex;
3310             break;
3311         }
3312     }
3313 }
3314 
updateCachedPixelExecutableIndex()3315 void ProgramD3D::updateCachedPixelExecutableIndex()
3316 {
3317     mCachedPixelExecutableIndex.reset();
3318     for (size_t executableIndex = 0; executableIndex < mPixelExecutables.size(); executableIndex++)
3319     {
3320         if (mPixelExecutables[executableIndex]->matchesSignature(mPixelShaderOutputLayoutCache))
3321         {
3322             mCachedPixelExecutableIndex = executableIndex;
3323             break;
3324         }
3325     }
3326 }
3327 
updateCachedComputeExecutableIndex()3328 void ProgramD3D::updateCachedComputeExecutableIndex()
3329 {
3330     mCachedComputeExecutableIndex.reset();
3331     for (size_t executableIndex = 0; executableIndex < mComputeExecutables.size();
3332          executableIndex++)
3333     {
3334         if (mComputeExecutables[executableIndex]->matchesSignature(
3335                 mComputeShaderImage2DBindLayoutCache))
3336         {
3337             mCachedComputeExecutableIndex = executableIndex;
3338             break;
3339         }
3340     }
3341 }
3342 
linkResources(const gl::ProgramLinkedResources & resources)3343 void ProgramD3D::linkResources(const gl::ProgramLinkedResources &resources)
3344 {
3345     HLSLBlockLayoutEncoderFactory hlslEncoderFactory;
3346     gl::ProgramLinkedResourcesLinker linker(&hlslEncoderFactory);
3347 
3348     linker.linkResources(mState, resources);
3349 
3350     initializeUniformBlocks();
3351     initializeShaderStorageBlocks();
3352 }
3353 
3354 }  // namespace rx
3355