shader_ir.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. // Copyright 2018 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <array>
  6. #include <cstring>
  7. #include <map>
  8. #include <optional>
  9. #include <set>
  10. #include <string>
  11. #include <tuple>
  12. #include <variant>
  13. #include <vector>
  14. #include "common/common_types.h"
  15. #include "video_core/engines/maxwell_3d.h"
  16. #include "video_core/engines/shader_bytecode.h"
  17. #include "video_core/engines/shader_header.h"
  18. namespace VideoCommon::Shader {
  19. class OperationNode;
  20. class ConditionalNode;
  21. class GprNode;
  22. class ImmediateNode;
  23. class InternalFlagNode;
  24. class PredicateNode;
  25. class AbufNode; ///< Attribute buffer
  26. class CbufNode; ///< Constant buffer
  27. class LmemNode; ///< Local memory
  28. class GmemNode; ///< Global memory
  29. class CommentNode;
  30. using ProgramCode = std::vector<u64>;
  31. using NodeData =
  32. std::variant<OperationNode, ConditionalNode, GprNode, ImmediateNode, InternalFlagNode,
  33. PredicateNode, AbufNode, CbufNode, LmemNode, GmemNode, CommentNode>;
  34. using Node = const NodeData*;
  35. using Node4 = std::array<Node, 4>;
  36. using NodeBlock = std::vector<Node>;
  37. constexpr u32 MAX_PROGRAM_LENGTH = 0x1000;
  38. enum class OperationCode {
  39. Assign, /// (float& dest, float src) -> void
  40. Select, /// (MetaArithmetic, bool pred, float a, float b) -> float
  41. FAdd, /// (MetaArithmetic, float a, float b) -> float
  42. FMul, /// (MetaArithmetic, float a, float b) -> float
  43. FDiv, /// (MetaArithmetic, float a, float b) -> float
  44. FFma, /// (MetaArithmetic, float a, float b, float c) -> float
  45. FNegate, /// (MetaArithmetic, float a) -> float
  46. FAbsolute, /// (MetaArithmetic, float a) -> float
  47. FClamp, /// (MetaArithmetic, float value, float min, float max) -> float
  48. FMin, /// (MetaArithmetic, float a, float b) -> float
  49. FMax, /// (MetaArithmetic, float a, float b) -> float
  50. FCos, /// (MetaArithmetic, float a) -> float
  51. FSin, /// (MetaArithmetic, float a) -> float
  52. FExp2, /// (MetaArithmetic, float a) -> float
  53. FLog2, /// (MetaArithmetic, float a) -> float
  54. FInverseSqrt, /// (MetaArithmetic, float a) -> float
  55. FSqrt, /// (MetaArithmetic, float a) -> float
  56. FRoundEven, /// (MetaArithmetic, float a) -> float
  57. FFloor, /// (MetaArithmetic, float a) -> float
  58. FCeil, /// (MetaArithmetic, float a) -> float
  59. FTrunc, /// (MetaArithmetic, float a) -> float
  60. FCastInteger, /// (MetaArithmetic, int a) -> float
  61. FCastUInteger, /// (MetaArithmetic, uint a) -> float
  62. IAdd, /// (MetaArithmetic, int a, int b) -> int
  63. IMul, /// (MetaArithmetic, int a, int b) -> int
  64. IDiv, /// (MetaArithmetic, int a, int b) -> int
  65. INegate, /// (MetaArithmetic, int a) -> int
  66. IAbsolute, /// (MetaArithmetic, int a) -> int
  67. IMin, /// (MetaArithmetic, int a, int b) -> int
  68. IMax, /// (MetaArithmetic, int a, int b) -> int
  69. ICastFloat, /// (MetaArithmetic, float a) -> int
  70. ICastUnsigned, /// (MetaArithmetic, uint a) -> int
  71. ILogicalShiftLeft, /// (MetaArithmetic, int a, uint b) -> int
  72. ILogicalShiftRight, /// (MetaArithmetic, int a, uint b) -> int
  73. IArithmeticShiftRight, /// (MetaArithmetic, int a, uint b) -> int
  74. IBitwiseAnd, /// (MetaArithmetic, int a, int b) -> int
  75. IBitwiseOr, /// (MetaArithmetic, int a, int b) -> int
  76. IBitwiseXor, /// (MetaArithmetic, int a, int b) -> int
  77. IBitwiseNot, /// (MetaArithmetic, int a) -> int
  78. IBitfieldInsert, /// (MetaArithmetic, int base, int insert, int offset, int bits) -> int
  79. IBitfieldExtract, /// (MetaArithmetic, int value, int offset, int offset) -> int
  80. IBitCount, /// (MetaArithmetic, int) -> int
  81. UAdd, /// (MetaArithmetic, uint a, uint b) -> uint
  82. UMul, /// (MetaArithmetic, uint a, uint b) -> uint
  83. UDiv, /// (MetaArithmetic, uint a, uint b) -> uint
  84. UMin, /// (MetaArithmetic, uint a, uint b) -> uint
  85. UMax, /// (MetaArithmetic, uint a, uint b) -> uint
  86. UCastFloat, /// (MetaArithmetic, float a) -> uint
  87. UCastSigned, /// (MetaArithmetic, int a) -> uint
  88. ULogicalShiftLeft, /// (MetaArithmetic, uint a, uint b) -> uint
  89. ULogicalShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
  90. UArithmeticShiftRight, /// (MetaArithmetic, uint a, uint b) -> uint
  91. UBitwiseAnd, /// (MetaArithmetic, uint a, uint b) -> uint
  92. UBitwiseOr, /// (MetaArithmetic, uint a, uint b) -> uint
  93. UBitwiseXor, /// (MetaArithmetic, uint a, uint b) -> uint
  94. UBitwiseNot, /// (MetaArithmetic, uint a) -> uint
  95. UBitfieldInsert, /// (MetaArithmetic, uint base, uint insert, int offset, int bits) -> uint
  96. UBitfieldExtract, /// (MetaArithmetic, uint value, int offset, int offset) -> uint
  97. UBitCount, /// (MetaArithmetic, uint) -> uint
  98. HAdd, /// (MetaArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
  99. HMul, /// (MetaArithmetic, f16vec2 a, f16vec2 b) -> f16vec2
  100. HFma, /// (MetaArithmetic, f16vec2 a, f16vec2 b, f16vec2 c) -> f16vec2
  101. HAbsolute, /// (f16vec2 a) -> f16vec2
  102. HNegate, /// (f16vec2 a, bool first, bool second) -> f16vec2
  103. HClamp, /// (f16vec2 src, float min, float max) -> f16vec2
  104. HUnpack, /// (Tegra::Shader::HalfType, T value) -> f16vec2
  105. HMergeF32, /// (f16vec2 src) -> float
  106. HMergeH0, /// (f16vec2 dest, f16vec2 src) -> f16vec2
  107. HMergeH1, /// (f16vec2 dest, f16vec2 src) -> f16vec2
  108. HPack2, /// (float a, float b) -> f16vec2
  109. LogicalAssign, /// (bool& dst, bool src) -> void
  110. LogicalAnd, /// (bool a, bool b) -> bool
  111. LogicalOr, /// (bool a, bool b) -> bool
  112. LogicalXor, /// (bool a, bool b) -> bool
  113. LogicalNegate, /// (bool a) -> bool
  114. LogicalPick2, /// (bool2 pair, uint index) -> bool
  115. LogicalAll2, /// (bool2 a) -> bool
  116. LogicalAny2, /// (bool2 a) -> bool
  117. LogicalFLessThan, /// (float a, float b) -> bool
  118. LogicalFEqual, /// (float a, float b) -> bool
  119. LogicalFLessEqual, /// (float a, float b) -> bool
  120. LogicalFGreaterThan, /// (float a, float b) -> bool
  121. LogicalFNotEqual, /// (float a, float b) -> bool
  122. LogicalFGreaterEqual, /// (float a, float b) -> bool
  123. LogicalFIsNan, /// (float a) -> bool
  124. LogicalILessThan, /// (int a, int b) -> bool
  125. LogicalIEqual, /// (int a, int b) -> bool
  126. LogicalILessEqual, /// (int a, int b) -> bool
  127. LogicalIGreaterThan, /// (int a, int b) -> bool
  128. LogicalINotEqual, /// (int a, int b) -> bool
  129. LogicalIGreaterEqual, /// (int a, int b) -> bool
  130. LogicalULessThan, /// (uint a, uint b) -> bool
  131. LogicalUEqual, /// (uint a, uint b) -> bool
  132. LogicalULessEqual, /// (uint a, uint b) -> bool
  133. LogicalUGreaterThan, /// (uint a, uint b) -> bool
  134. LogicalUNotEqual, /// (uint a, uint b) -> bool
  135. LogicalUGreaterEqual, /// (uint a, uint b) -> bool
  136. Logical2HLessThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  137. Logical2HEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  138. Logical2HLessEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  139. Logical2HGreaterThan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  140. Logical2HNotEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  141. Logical2HGreaterEqual, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  142. Logical2HLessThanWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  143. Logical2HEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  144. Logical2HLessEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  145. Logical2HGreaterThanWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  146. Logical2HNotEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  147. Logical2HGreaterEqualWithNan, /// (MetaHalfArithmetic, f16vec2 a, f16vec2) -> bool2
  148. Texture, /// (MetaTexture, float[N] coords) -> float4
  149. TextureLod, /// (MetaTexture, float[N] coords) -> float4
  150. TextureGather, /// (MetaTexture, float[N] coords) -> float4
  151. TextureQueryDimensions, /// (MetaTexture, float a) -> float4
  152. TextureQueryLod, /// (MetaTexture, float[N] coords) -> float4
  153. TexelFetch, /// (MetaTexture, int[N], int) -> float4
  154. Branch, /// (uint branch_target) -> void
  155. PushFlowStack, /// (uint branch_target) -> void
  156. PopFlowStack, /// () -> void
  157. Exit, /// () -> void
  158. Discard, /// () -> void
  159. EmitVertex, /// () -> void
  160. EndPrimitive, /// () -> void
  161. YNegate, /// () -> float
  162. Amount,
  163. };
  164. enum class InternalFlag {
  165. Zero = 0,
  166. Sign = 1,
  167. Carry = 2,
  168. Overflow = 3,
  169. Amount = 4,
  170. };
  171. /// Describes the behaviour of code path of a given entry point and a return point.
  172. enum class ExitMethod {
  173. Undetermined, ///< Internal value. Only occur when analyzing JMP loop.
  174. AlwaysReturn, ///< All code paths reach the return point.
  175. Conditional, ///< Code path reaches the return point or an END instruction conditionally.
  176. AlwaysEnd, ///< All code paths reach a END instruction.
  177. };
  178. class Sampler {
  179. public:
  180. // Use this constructor for bounded Samplers
  181. explicit Sampler(std::size_t offset, std::size_t index, Tegra::Shader::TextureType type,
  182. bool is_array, bool is_shadow)
  183. : offset{offset}, index{index}, type{type}, is_array{is_array}, is_shadow{is_shadow},
  184. is_bindless{false} {}
  185. // Use this constructor for bindless Samplers
  186. explicit Sampler(u32 cbuf_index, u32 cbuf_offset, std::size_t index,
  187. Tegra::Shader::TextureType type, bool is_array, bool is_shadow)
  188. : offset{(static_cast<u64>(cbuf_index) << 32) | cbuf_offset}, index{index}, type{type},
  189. is_array{is_array}, is_shadow{is_shadow}, is_bindless{true} {}
  190. // Use this only for serialization/deserialization
  191. explicit Sampler(std::size_t offset, std::size_t index, Tegra::Shader::TextureType type,
  192. bool is_array, bool is_shadow, bool is_bindless)
  193. : offset{offset}, index{index}, type{type}, is_array{is_array}, is_shadow{is_shadow},
  194. is_bindless{is_bindless} {}
  195. std::size_t GetOffset() const {
  196. return offset;
  197. }
  198. std::size_t GetIndex() const {
  199. return index;
  200. }
  201. Tegra::Shader::TextureType GetType() const {
  202. return type;
  203. }
  204. bool IsArray() const {
  205. return is_array;
  206. }
  207. bool IsShadow() const {
  208. return is_shadow;
  209. }
  210. bool IsBindless() const {
  211. return is_bindless;
  212. }
  213. std::pair<u32, u32> GetBindlessCBuf() const {
  214. return {static_cast<u32>(offset >> 32), static_cast<u32>(offset)};
  215. }
  216. bool operator<(const Sampler& rhs) const {
  217. return std::tie(index, offset, type, is_array, is_shadow, is_bindless) <
  218. std::tie(rhs.index, rhs.offset, rhs.type, rhs.is_array, rhs.is_shadow,
  219. rhs.is_bindless);
  220. }
  221. private:
  222. /// Offset in TSC memory from which to read the sampler object, as specified by the sampling
  223. /// instruction.
  224. std::size_t offset{};
  225. std::size_t index{}; ///< Value used to index into the generated GLSL sampler array.
  226. Tegra::Shader::TextureType type{}; ///< The type used to sample this texture (Texture2D, etc)
  227. bool is_array{}; ///< Whether the texture is being sampled as an array texture or not.
  228. bool is_shadow{}; ///< Whether the texture is being sampled as a depth texture or not.
  229. bool is_bindless{}; ///< Whether this sampler belongs to a bindless texture or not.
  230. };
  231. class ConstBuffer {
  232. public:
  233. explicit ConstBuffer(u32 max_offset, bool is_indirect)
  234. : max_offset{max_offset}, is_indirect{is_indirect} {}
  235. ConstBuffer() = default;
  236. void MarkAsUsed(u64 offset) {
  237. max_offset = std::max(max_offset, static_cast<u32>(offset));
  238. }
  239. void MarkAsUsedIndirect() {
  240. is_indirect = true;
  241. }
  242. bool IsIndirect() const {
  243. return is_indirect;
  244. }
  245. u32 GetSize() const {
  246. return max_offset + sizeof(float);
  247. }
  248. u32 GetMaxOffset() const {
  249. return max_offset;
  250. }
  251. private:
  252. u32 max_offset{};
  253. bool is_indirect{};
  254. };
  255. struct GlobalMemoryBase {
  256. u32 cbuf_index{};
  257. u32 cbuf_offset{};
  258. bool operator<(const GlobalMemoryBase& rhs) const {
  259. return std::tie(cbuf_index, cbuf_offset) < std::tie(rhs.cbuf_index, rhs.cbuf_offset);
  260. }
  261. };
  262. struct GlobalMemoryUsage {
  263. bool is_read{};
  264. bool is_written{};
  265. };
  266. struct MetaArithmetic {
  267. bool precise{};
  268. };
  269. struct MetaTexture {
  270. const Sampler& sampler;
  271. Node array{};
  272. Node depth_compare{};
  273. std::vector<Node> aoffi;
  274. Node bias{};
  275. Node lod{};
  276. Node component{};
  277. u32 element{};
  278. };
  279. constexpr MetaArithmetic PRECISE = {true};
  280. constexpr MetaArithmetic NO_PRECISE = {false};
  281. using Meta = std::variant<MetaArithmetic, MetaTexture, Tegra::Shader::HalfType>;
  282. /// Holds any kind of operation that can be done in the IR
  283. class OperationNode final {
  284. public:
  285. explicit OperationNode(OperationCode code) : code{code} {}
  286. explicit OperationNode(OperationCode code, Meta&& meta) : code{code}, meta{std::move(meta)} {}
  287. template <typename... T>
  288. explicit OperationNode(OperationCode code, const T*... operands)
  289. : OperationNode(code, {}, operands...) {}
  290. template <typename... T>
  291. explicit OperationNode(OperationCode code, Meta&& meta, const T*... operands_)
  292. : code{code}, meta{std::move(meta)}, operands{operands_...} {}
  293. explicit OperationNode(OperationCode code, Meta&& meta, std::vector<Node>&& operands)
  294. : code{code}, meta{meta}, operands{std::move(operands)} {}
  295. explicit OperationNode(OperationCode code, std::vector<Node>&& operands)
  296. : code{code}, operands{std::move(operands)} {}
  297. OperationCode GetCode() const {
  298. return code;
  299. }
  300. const Meta& GetMeta() const {
  301. return meta;
  302. }
  303. std::size_t GetOperandsCount() const {
  304. return operands.size();
  305. }
  306. Node operator[](std::size_t operand_index) const {
  307. return operands.at(operand_index);
  308. }
  309. private:
  310. const OperationCode code;
  311. const Meta meta;
  312. std::vector<Node> operands;
  313. };
  314. /// Encloses inside any kind of node that returns a boolean conditionally-executed code
  315. class ConditionalNode final {
  316. public:
  317. explicit ConditionalNode(Node condition, std::vector<Node>&& code)
  318. : condition{condition}, code{std::move(code)} {}
  319. Node GetCondition() const {
  320. return condition;
  321. }
  322. const std::vector<Node>& GetCode() const {
  323. return code;
  324. }
  325. private:
  326. const Node condition; ///< Condition to be satisfied
  327. std::vector<Node> code; ///< Code to execute
  328. };
  329. /// A general purpose register
  330. class GprNode final {
  331. public:
  332. explicit constexpr GprNode(Tegra::Shader::Register index) : index{index} {}
  333. u32 GetIndex() const {
  334. return static_cast<u32>(index);
  335. }
  336. private:
  337. const Tegra::Shader::Register index;
  338. };
  339. /// A 32-bits value that represents an immediate value
  340. class ImmediateNode final {
  341. public:
  342. explicit constexpr ImmediateNode(u32 value) : value{value} {}
  343. u32 GetValue() const {
  344. return value;
  345. }
  346. private:
  347. const u32 value;
  348. };
  349. /// One of Maxwell's internal flags
  350. class InternalFlagNode final {
  351. public:
  352. explicit constexpr InternalFlagNode(InternalFlag flag) : flag{flag} {}
  353. InternalFlag GetFlag() const {
  354. return flag;
  355. }
  356. private:
  357. const InternalFlag flag;
  358. };
  359. /// A predicate register, it can be negated without additional nodes
  360. class PredicateNode final {
  361. public:
  362. explicit constexpr PredicateNode(Tegra::Shader::Pred index, bool negated)
  363. : index{index}, negated{negated} {}
  364. Tegra::Shader::Pred GetIndex() const {
  365. return index;
  366. }
  367. bool IsNegated() const {
  368. return negated;
  369. }
  370. private:
  371. const Tegra::Shader::Pred index;
  372. const bool negated;
  373. };
  374. /// Attribute buffer memory (known as attributes or varyings in GLSL terms)
  375. class AbufNode final {
  376. public:
  377. // Initialize for standard attributes (index is explicit).
  378. explicit constexpr AbufNode(Tegra::Shader::Attribute::Index index, u32 element,
  379. Node buffer = {})
  380. : buffer{buffer}, index{index}, element{element} {}
  381. // Initialize for physical attributes (index is a variable value).
  382. explicit constexpr AbufNode(Node physical_address, Node buffer = {})
  383. : physical_address{physical_address}, buffer{buffer} {}
  384. Tegra::Shader::Attribute::Index GetIndex() const {
  385. return index;
  386. }
  387. u32 GetElement() const {
  388. return element;
  389. }
  390. Node GetBuffer() const {
  391. return buffer;
  392. }
  393. bool IsPhysicalBuffer() const {
  394. return physical_address != nullptr;
  395. }
  396. Node GetPhysicalAddress() const {
  397. return physical_address;
  398. }
  399. private:
  400. Node physical_address{};
  401. Node buffer{};
  402. Tegra::Shader::Attribute::Index index{};
  403. u32 element{};
  404. };
  405. /// Constant buffer node, usually mapped to uniform buffers in GLSL
  406. class CbufNode final {
  407. public:
  408. explicit constexpr CbufNode(u32 index, Node offset) : index{index}, offset{offset} {}
  409. u32 GetIndex() const {
  410. return index;
  411. }
  412. Node GetOffset() const {
  413. return offset;
  414. }
  415. private:
  416. const u32 index;
  417. const Node offset;
  418. };
  419. /// Local memory node
  420. class LmemNode final {
  421. public:
  422. explicit constexpr LmemNode(Node address) : address{address} {}
  423. Node GetAddress() const {
  424. return address;
  425. }
  426. private:
  427. const Node address;
  428. };
  429. /// Global memory node
  430. class GmemNode final {
  431. public:
  432. explicit constexpr GmemNode(Node real_address, Node base_address,
  433. const GlobalMemoryBase& descriptor)
  434. : real_address{real_address}, base_address{base_address}, descriptor{descriptor} {}
  435. Node GetRealAddress() const {
  436. return real_address;
  437. }
  438. Node GetBaseAddress() const {
  439. return base_address;
  440. }
  441. const GlobalMemoryBase& GetDescriptor() const {
  442. return descriptor;
  443. }
  444. private:
  445. const Node real_address;
  446. const Node base_address;
  447. const GlobalMemoryBase descriptor;
  448. };
  449. /// Commentary, can be dropped
  450. class CommentNode final {
  451. public:
  452. explicit CommentNode(std::string text) : text{std::move(text)} {}
  453. const std::string& GetText() const {
  454. return text;
  455. }
  456. private:
  457. std::string text;
  458. };
  459. class ShaderIR final {
  460. public:
  461. explicit ShaderIR(const ProgramCode& program_code, u32 main_offset);
  462. ~ShaderIR();
  463. const std::map<u32, NodeBlock>& GetBasicBlocks() const {
  464. return basic_blocks;
  465. }
  466. const std::set<u32>& GetRegisters() const {
  467. return used_registers;
  468. }
  469. const std::set<Tegra::Shader::Pred>& GetPredicates() const {
  470. return used_predicates;
  471. }
  472. const std::set<Tegra::Shader::Attribute::Index>& GetInputAttributes() const {
  473. return used_input_attributes;
  474. }
  475. const std::set<Tegra::Shader::Attribute::Index>& GetOutputAttributes() const {
  476. return used_output_attributes;
  477. }
  478. const std::map<u32, ConstBuffer>& GetConstantBuffers() const {
  479. return used_cbufs;
  480. }
  481. const std::set<Sampler>& GetSamplers() const {
  482. return used_samplers;
  483. }
  484. const std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances>& GetClipDistances()
  485. const {
  486. return used_clip_distances;
  487. }
  488. const std::map<GlobalMemoryBase, GlobalMemoryUsage>& GetGlobalMemory() const {
  489. return used_global_memory;
  490. }
  491. std::size_t GetLength() const {
  492. return static_cast<std::size_t>(coverage_end * sizeof(u64));
  493. }
  494. bool HasPhysicalAttributes() const {
  495. return uses_physical_attributes;
  496. }
  497. const Tegra::Shader::Header& GetHeader() const {
  498. return header;
  499. }
  500. private:
  501. void Decode();
  502. ExitMethod Scan(u32 begin, u32 end, std::set<u32>& labels);
  503. NodeBlock DecodeRange(u32 begin, u32 end);
  504. /**
  505. * Decodes a single instruction from Tegra to IR.
  506. * @param bb Basic block where the nodes will be written to.
  507. * @param pc Program counter. Offset to decode.
  508. * @return Next address to decode.
  509. */
  510. u32 DecodeInstr(NodeBlock& bb, u32 pc);
  511. u32 DecodeArithmetic(NodeBlock& bb, u32 pc);
  512. u32 DecodeArithmeticImmediate(NodeBlock& bb, u32 pc);
  513. u32 DecodeBfe(NodeBlock& bb, u32 pc);
  514. u32 DecodeBfi(NodeBlock& bb, u32 pc);
  515. u32 DecodeShift(NodeBlock& bb, u32 pc);
  516. u32 DecodeArithmeticInteger(NodeBlock& bb, u32 pc);
  517. u32 DecodeArithmeticIntegerImmediate(NodeBlock& bb, u32 pc);
  518. u32 DecodeArithmeticHalf(NodeBlock& bb, u32 pc);
  519. u32 DecodeArithmeticHalfImmediate(NodeBlock& bb, u32 pc);
  520. u32 DecodeFfma(NodeBlock& bb, u32 pc);
  521. u32 DecodeHfma2(NodeBlock& bb, u32 pc);
  522. u32 DecodeConversion(NodeBlock& bb, u32 pc);
  523. u32 DecodeMemory(NodeBlock& bb, u32 pc);
  524. u32 DecodeTexture(NodeBlock& bb, u32 pc);
  525. u32 DecodeFloatSetPredicate(NodeBlock& bb, u32 pc);
  526. u32 DecodeIntegerSetPredicate(NodeBlock& bb, u32 pc);
  527. u32 DecodeHalfSetPredicate(NodeBlock& bb, u32 pc);
  528. u32 DecodePredicateSetRegister(NodeBlock& bb, u32 pc);
  529. u32 DecodePredicateSetPredicate(NodeBlock& bb, u32 pc);
  530. u32 DecodeRegisterSetPredicate(NodeBlock& bb, u32 pc);
  531. u32 DecodeFloatSet(NodeBlock& bb, u32 pc);
  532. u32 DecodeIntegerSet(NodeBlock& bb, u32 pc);
  533. u32 DecodeHalfSet(NodeBlock& bb, u32 pc);
  534. u32 DecodeVideo(NodeBlock& bb, u32 pc);
  535. u32 DecodeXmad(NodeBlock& bb, u32 pc);
  536. u32 DecodeOther(NodeBlock& bb, u32 pc);
  537. /// Internalizes node's data and returns a managed pointer to a clone of that node
  538. Node StoreNode(NodeData&& node_data);
  539. /// Creates a conditional node
  540. Node Conditional(Node condition, std::vector<Node>&& code);
  541. /// Creates a commentary
  542. Node Comment(const std::string& text);
  543. /// Creates an u32 immediate
  544. Node Immediate(u32 value);
  545. /// Creates a s32 immediate
  546. Node Immediate(s32 value) {
  547. return Immediate(static_cast<u32>(value));
  548. }
  549. /// Creates a f32 immediate
  550. Node Immediate(f32 value) {
  551. u32 integral;
  552. std::memcpy(&integral, &value, sizeof(u32));
  553. return Immediate(integral);
  554. }
  555. /// Generates a node for a passed register.
  556. Node GetRegister(Tegra::Shader::Register reg);
  557. /// Generates a node representing a 19-bit immediate value
  558. Node GetImmediate19(Tegra::Shader::Instruction instr);
  559. /// Generates a node representing a 32-bit immediate value
  560. Node GetImmediate32(Tegra::Shader::Instruction instr);
  561. /// Generates a node representing a constant buffer
  562. Node GetConstBuffer(u64 index, u64 offset);
  563. /// Generates a node representing a constant buffer with a variadic offset
  564. Node GetConstBufferIndirect(u64 index, u64 offset, Node node);
  565. /// Generates a node for a passed predicate. It can be optionally negated
  566. Node GetPredicate(u64 pred, bool negated = false);
  567. /// Generates a predicate node for an immediate true or false value
  568. Node GetPredicate(bool immediate);
  569. /// Generates a node representing an input attribute. Keeps track of used attributes.
  570. Node GetInputAttribute(Tegra::Shader::Attribute::Index index, u64 element, Node buffer = {});
  571. /// Generates a node representing a physical input attribute.
  572. Node GetPhysicalInputAttribute(Tegra::Shader::Register physical_address, Node buffer = {});
  573. /// Generates a node representing an output attribute. Keeps track of used attributes.
  574. Node GetOutputAttribute(Tegra::Shader::Attribute::Index index, u64 element, Node buffer);
  575. /// Generates a node representing an internal flag
  576. Node GetInternalFlag(InternalFlag flag, bool negated = false);
  577. /// Generates a node representing a local memory address
  578. Node GetLocalMemory(Node address);
  579. /// Generates a temporal, internally it uses a post-RZ register
  580. Node GetTemporal(u32 id);
  581. /// Sets a register. src value must be a number-evaluated node.
  582. void SetRegister(NodeBlock& bb, Tegra::Shader::Register dest, Node src);
  583. /// Sets a predicate. src value must be a bool-evaluated node
  584. void SetPredicate(NodeBlock& bb, u64 dest, Node src);
  585. /// Sets an internal flag. src value must be a bool-evaluated node
  586. void SetInternalFlag(NodeBlock& bb, InternalFlag flag, Node value);
  587. /// Sets a local memory address. address and value must be a number-evaluated node
  588. void SetLocalMemory(NodeBlock& bb, Node address, Node value);
  589. /// Sets a temporal. Internally it uses a post-RZ register
  590. void SetTemporal(NodeBlock& bb, u32 id, Node value);
  591. /// Sets internal flags from a float
  592. void SetInternalFlagsFromFloat(NodeBlock& bb, Node value, bool sets_cc = true);
  593. /// Sets internal flags from an integer
  594. void SetInternalFlagsFromInteger(NodeBlock& bb, Node value, bool sets_cc = true);
  595. /// Conditionally absolute/negated float. Absolute is applied first
  596. Node GetOperandAbsNegFloat(Node value, bool absolute, bool negate);
  597. /// Conditionally saturates a float
  598. Node GetSaturatedFloat(Node value, bool saturate = true);
  599. /// Converts an integer to different sizes.
  600. Node ConvertIntegerSize(Node value, Tegra::Shader::Register::Size size, bool is_signed);
  601. /// Conditionally absolute/negated integer. Absolute is applied first
  602. Node GetOperandAbsNegInteger(Node value, bool absolute, bool negate, bool is_signed);
  603. /// Unpacks a half immediate from an instruction
  604. Node UnpackHalfImmediate(Tegra::Shader::Instruction instr, bool has_negation);
  605. /// Unpacks a binary value into a half float pair with a type format
  606. Node UnpackHalfFloat(Node value, Tegra::Shader::HalfType type);
  607. /// Merges a half pair into another value
  608. Node HalfMerge(Node dest, Node src, Tegra::Shader::HalfMerge merge);
  609. /// Conditionally absolute/negated half float pair. Absolute is applied first
  610. Node GetOperandAbsNegHalf(Node value, bool absolute, bool negate);
  611. /// Conditionally saturates a half float pair
  612. Node GetSaturatedHalfFloat(Node value, bool saturate = true);
  613. /// Returns a predicate comparing two floats
  614. Node GetPredicateComparisonFloat(Tegra::Shader::PredCondition condition, Node op_a, Node op_b);
  615. /// Returns a predicate comparing two integers
  616. Node GetPredicateComparisonInteger(Tegra::Shader::PredCondition condition, bool is_signed,
  617. Node op_a, Node op_b);
  618. /// Returns a predicate comparing two half floats. meta consumes how both pairs will be compared
  619. Node GetPredicateComparisonHalf(Tegra::Shader::PredCondition condition, Node op_a, Node op_b);
  620. /// Returns a predicate combiner operation
  621. OperationCode GetPredicateCombiner(Tegra::Shader::PredOperation operation);
  622. /// Returns a condition code evaluated from internal flags
  623. Node GetConditionCode(Tegra::Shader::ConditionCode cc);
  624. /// Accesses a texture sampler
  625. const Sampler& GetSampler(const Tegra::Shader::Sampler& sampler,
  626. Tegra::Shader::TextureType type, bool is_array, bool is_shadow);
  627. // Accesses a texture sampler for a bindless texture.
  628. const Sampler& GetBindlessSampler(const Tegra::Shader::Register& reg,
  629. Tegra::Shader::TextureType type, bool is_array,
  630. bool is_shadow);
  631. /// Extracts a sequence of bits from a node
  632. Node BitfieldExtract(Node value, u32 offset, u32 bits);
  633. void WriteTexInstructionFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  634. const Node4& components);
  635. void WriteTexsInstructionFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  636. const Node4& components);
  637. void WriteTexsInstructionHalfFloat(NodeBlock& bb, Tegra::Shader::Instruction instr,
  638. const Node4& components);
  639. Node4 GetTexCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  640. Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
  641. bool is_array, bool is_aoffi,
  642. std::optional<Tegra::Shader::Register> bindless_reg);
  643. Node4 GetTexsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  644. Tegra::Shader::TextureProcessMode process_mode, bool depth_compare,
  645. bool is_array);
  646. Node4 GetTld4Code(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  647. bool depth_compare, bool is_array, bool is_aoffi);
  648. Node4 GetTldsCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  649. bool is_array);
  650. std::tuple<std::size_t, std::size_t> ValidateAndGetCoordinateElement(
  651. Tegra::Shader::TextureType texture_type, bool depth_compare, bool is_array,
  652. bool lod_bias_enabled, std::size_t max_coords, std::size_t max_inputs);
  653. std::vector<Node> GetAoffiCoordinates(Node aoffi_reg, std::size_t coord_count, bool is_tld4);
  654. Node4 GetTextureCode(Tegra::Shader::Instruction instr, Tegra::Shader::TextureType texture_type,
  655. Tegra::Shader::TextureProcessMode process_mode, std::vector<Node> coords,
  656. Node array, Node depth_compare, u32 bias_offset, std::vector<Node> aoffi,
  657. std::optional<Tegra::Shader::Register> bindless_reg);
  658. Node GetVideoOperand(Node op, bool is_chunk, bool is_signed, Tegra::Shader::VideoType type,
  659. u64 byte_height);
  660. void WriteLogicOperation(NodeBlock& bb, Tegra::Shader::Register dest,
  661. Tegra::Shader::LogicOperation logic_op, Node op_a, Node op_b,
  662. Tegra::Shader::PredicateResultMode predicate_mode,
  663. Tegra::Shader::Pred predicate, bool sets_cc);
  664. void WriteLop3Instruction(NodeBlock& bb, Tegra::Shader::Register dest, Node op_a, Node op_b,
  665. Node op_c, Node imm_lut, bool sets_cc);
  666. Node TrackCbuf(Node tracked, const NodeBlock& code, s64 cursor) const;
  667. std::optional<u32> TrackImmediate(Node tracked, const NodeBlock& code, s64 cursor) const;
  668. std::pair<Node, s64> TrackRegister(const GprNode* tracked, const NodeBlock& code,
  669. s64 cursor) const;
  670. std::tuple<Node, Node, GlobalMemoryBase> TrackAndGetGlobalMemory(NodeBlock& bb,
  671. Node addr_register,
  672. u32 immediate_offset,
  673. bool is_write);
  674. template <typename... T>
  675. Node Operation(OperationCode code, const T*... operands) {
  676. return StoreNode(OperationNode(code, operands...));
  677. }
  678. template <typename... T>
  679. Node Operation(OperationCode code, Meta&& meta, const T*... operands) {
  680. return StoreNode(OperationNode(code, std::move(meta), operands...));
  681. }
  682. Node Operation(OperationCode code, std::vector<Node>&& operands) {
  683. return StoreNode(OperationNode(code, std::move(operands)));
  684. }
  685. Node Operation(OperationCode code, Meta&& meta, std::vector<Node>&& operands) {
  686. return StoreNode(OperationNode(code, std::move(meta), std::move(operands)));
  687. }
  688. template <typename... T>
  689. Node SignedOperation(OperationCode code, bool is_signed, const T*... operands) {
  690. return StoreNode(OperationNode(SignedToUnsignedCode(code, is_signed), operands...));
  691. }
  692. template <typename... T>
  693. Node SignedOperation(OperationCode code, bool is_signed, Meta&& meta, const T*... operands) {
  694. return StoreNode(
  695. OperationNode(SignedToUnsignedCode(code, is_signed), std::move(meta), operands...));
  696. }
  697. static OperationCode SignedToUnsignedCode(OperationCode operation_code, bool is_signed);
  698. const ProgramCode& program_code;
  699. const u32 main_offset;
  700. u32 coverage_begin{};
  701. u32 coverage_end{};
  702. std::map<std::pair<u32, u32>, ExitMethod> exit_method_map;
  703. std::map<u32, NodeBlock> basic_blocks;
  704. NodeBlock global_code;
  705. std::vector<std::unique_ptr<NodeData>> stored_nodes;
  706. std::set<u32> used_registers;
  707. std::set<Tegra::Shader::Pred> used_predicates;
  708. std::set<Tegra::Shader::Attribute::Index> used_input_attributes;
  709. std::set<Tegra::Shader::Attribute::Index> used_output_attributes;
  710. std::map<u32, ConstBuffer> used_cbufs;
  711. std::set<Sampler> used_samplers;
  712. std::array<bool, Tegra::Engines::Maxwell3D::Regs::NumClipDistances> used_clip_distances{};
  713. std::map<GlobalMemoryBase, GlobalMemoryUsage> used_global_memory;
  714. bool uses_physical_attributes{}; // Shader uses AL2P or physical attribute read/writes
  715. Tegra::Shader::Header header;
  716. };
  717. } // namespace VideoCommon::Shader