1 //
2 // Copyright 2011 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 #ifndef COMPILER_TRANSLATOR_BUILTINFUNCTIONEMULATOR_H_
8 #define COMPILER_TRANSLATOR_BUILTINFUNCTIONEMULATOR_H_
9 
10 #include "compiler/translator/InfoSink.h"
11 
12 namespace sh
13 {
14 
15 class TIntermNode;
16 class TFunction;
17 class TSymbolUniqueId;
18 
19 using BuiltinQueryFunc = const char *(int);
20 
21 //
22 // This class decides which built-in functions need to be replaced with the emulated ones. It can be
23 // used to work around driver bugs or implement functions that are not natively implemented on a
24 // specific platform.
25 //
26 class BuiltInFunctionEmulator
27 {
28   public:
29     BuiltInFunctionEmulator();
30 
31     void markBuiltInFunctionsForEmulation(TIntermNode *root);
32 
33     void cleanup();
34 
35     // "name" gets written as "name_emu".
36     static void WriteEmulatedFunctionName(TInfoSinkBase &out, const char *name);
37 
38     bool isOutputEmpty() const;
39 
40     // Output function emulation definition. This should be before any other shader source.
41     void outputEmulatedFunctions(TInfoSinkBase &out) const;
42 
43     // Add functions that need to be emulated.
44     void addEmulatedFunction(const TSymbolUniqueId &uniqueId,
45                              const char *emulatedFunctionDefinition);
46 
47     void addEmulatedFunctionWithDependency(const TSymbolUniqueId &dependency,
48                                            const TSymbolUniqueId &uniqueId,
49                                            const char *emulatedFunctionDefinition);
50 
51     void addFunctionMap(BuiltinQueryFunc queryFunc);
52 
53   private:
54     class BuiltInFunctionEmulationMarker;
55 
56     // Records that a function is called by the shader and might need to be emulated. If the
57     // function is not in mEmulatedFunctions, this becomes a no-op. Returns true if the function
58     // call needs to be replaced with an emulated one.
59     bool setFunctionCalled(const TFunction *function);
60     bool setFunctionCalled(int uniqueId);
61 
62     const char *findEmulatedFunction(int uniqueId) const;
63 
64     // Map from function unique id to emulated function definition
65     std::map<int, std::string> mEmulatedFunctions;
66 
67     // Map from dependent functions to their dependencies. This structure allows each function to
68     // have at most one dependency.
69     std::map<int, int> mFunctionDependencies;
70 
71     // Called function ids
72     std::vector<int> mFunctions;
73 
74     // Constexpr function tables.
75     std::vector<BuiltinQueryFunc *> mQueryFunctions;
76 };
77 
78 }  // namespace sh
79 
80 #endif  // COMPILER_TRANSLATOR_BUILTINFUNCTIONEMULATOR_H_
81