DXIL.rst 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976
  1. =============================
  2. DirectX Intermediate Language
  3. =============================
  4. .. contents::
  5. :local:
  6. :depth: 2
  7. Introduction
  8. ============
  9. This document presents the design of the DirectX Intermediate Language (DXIL) for GPU shaders. DXIL is intended to support a direct mapping of the HLSL programming language into Low-Level Virtual Machine Intermediate Representation (LLVM IR), suitable for consumption in GPU drivers. This version of the specification is based on LLVM 3.7 in the use of metadata syntax.
  10. We distinguish between DXIL, which is a low-level IR for GPU driver compilers, and DXIR, which is a high-level IR, more suitable for emission by IR producers, such as Clang. DXIR is transformed to DXIL by the optimizer. DXIR accepts high-level constructs, such as user-defined types, multi-dimensional arrays, matrices, and vectors. These, however, are not suitable for fast JIT-ing in the driver compilers, and so are lowered by the optimizer, such that DXIL works on simpler abstractions. Both DXIL and DXIR are derived from LLVM IR. This document does not describe DXIR.
  11. LLVM is quickly becoming a de facto standard in modern compilation technology. The LLVM framework offers several distinct features, such as a vibrant ecosystem, complete compilation framework, modular design, and reasonable documentation. We can leverage these to achieve two important objectives.
  12. First, unification of shader compilation tool chain. DXIL is a contract between IR producers, such as compilers for HLSL and other domain-specific languages, and IR consumers, such as IHV driver JIT compilers or offline XBOX shader compiler. In addition, the design provides for conversion the current HLSL IL, called DXBC IL in this document, and DXIL.
  13. Second, leveraging the LLVM ecosystem. Microsoft will publicly document DXIL and DXIR to attract domain language implementers and spur innovation. Using LLVM-based IR offers reduced entry costs for small teams, simply because small teams are likely to use LLVM and Clang as their main compilation framework. We will provide DXIL verifier to check consistency of generated DXIL.
  14. The following diagram shows how some of these components tie together::
  15. HLSL Other shading langs DSL DXBC IL
  16. + + + +
  17. | | | |
  18. v v v v
  19. Clang Clang Other Tools dxbc2dxil
  20. + + + +
  21. | | | |
  22. v v v |
  23. +------+--------------------+---------+ |
  24. | High level IR (DXIR) | |
  25. +-------------------------------------+ |
  26. | |
  27. | |
  28. v |
  29. Optimizer <-----+ Linker |
  30. + ^ + |
  31. | | | |
  32. | | | |
  33. +------------v------+-------------v-----v-------+
  34. | Low|level IR (DXIL) |
  35. +------------+----------------------+-----------+
  36. | |
  37. v v
  38. Driver Compiler Verifier
  39. The *dxbc2dxil* element in the diagram is a component that converts existing DXBC shader byte code into DXIL. The *Optimizer* element is a component that consumes DXIR, verifies it is valid, optimizes it, and produces a valid DXIL form. The *Verifier* element is a public component that verifies DXIL. The *Linker* is a component that combines precompiled DXIL libraries with the entry function to produce a valid shader.
  40. DXIL does not support the following HLSL features that were present in prior implementations.
  41. * Shader models 9 and below. Microsoft may implement 10level9 shader models via DXIL capability tiers.
  42. * Effects.
  43. * HLSL interfaces.
  44. * Shader compression/decompression.
  45. * Partial precision. Half data type should be used instead.
  46. * min10float type. Half data type should be used instead.
  47. * HLSL *uniform* parameter qualifier.
  48. * Current fxc legacy compatibility mode for old shader models (e.g., c-register binding).
  49. * PDB. Debug Information annotations are used instead.
  50. * Compute shader model cs_4_0.
  51. * DXBC label, call, fcall constructs.
  52. The following principles are used to ease reuse with LLVM components and aid extensibility.
  53. * DXIL uses a subset of LLVM IR constructs that makes sense for HLSL.
  54. * No modifications to the core LLVM IR; i.e., no new instructions or fundamental types.
  55. * Additional information is conveyed via metadata, LLVM intrinsics or external functions.
  56. * Name prefixes: 'llvm.dx.', 'llvm.dxil.', 'llvm.dxir.', 'dx.', 'dxil.', and 'dxir.' are reserved.
  57. LLVM IR has three equivalent forms: human-readable, binary (bitcode), and in-memory. DXIL is a binary format and is based on a subset of LLVM IR bitcode format. The document uses only human-readable form to describe DXIL.
  58. Versioning
  59. ==========
  60. There are three versioning mechanisms in DXIL shaders: shader model, DXIL version, and LLVM bitcode version.
  61. At a high-level, the shader model describes the target execution model and environment; DXIL provides a mechanism to express programs (including rules around expressing data types and operations); and LLVM bitcode provides a way to encode a DXIL program.
  62. Shader Model
  63. ------------
  64. The shader model in DXIL is similar to DXBC shader model. A shader model specifies the execution model, the set of capabilities that shader instructions can use and the constraints that a shader program must adhere to.
  65. The shader model is specified as a named metadata in DXIL::
  66. !dx.shaderModel = !{ !0 }
  67. !0 = !{ !"<shadelModelName>", i32 <major>, i32 <minor> }
  68. The following values of <shaderModelName>_<major>_<minor> are supported:
  69. ==================== ===================================== ===========
  70. Target Legacy Models DXIL Models
  71. ==================== ===================================== ===========
  72. Vertex shader (VS) vs_4_0, vs_4_1, vs_5_0, vs_5_1 vs_6_0
  73. Hull shader (HS) hs_5_0, hs_5_1 hs_6_0
  74. Domain shader (DS) ds_5_0, ds_5_1 ds_6_0
  75. Geometry shader (GS) gs_4_0, gs_4_1, gs_5_0, gs_5_1 gs_6_0
  76. Pixel shader (PS) ps_4_0, ps_4_1, ps_5_0, ps_5_1 ps_6_0
  77. Compute shader (CS) cs_5_0 (cs_4_0 is mapped onto cs_5_0) cs_6_0
  78. Shader library no support no support
  79. ==================== ===================================== ===========
  80. The DXIL verifier ensures that DXIL conforms to the specified shader model.
  81. For shader models prior to 6.0, only the rules applicable to the DXIL representation are valid. For example, the limits on maximum number of resources is honored, but the limits on registers aren't because DXIL does not have a representation for registers.
  82. DXIL version
  83. ------------
  84. The primary mechanism to evolve HLSL capabilities is through shader models. However, DXIL version is reserved for additional flexibility of future extensions. The only currently defined version is 1.0.
  85. DXIL version has major and minor versions that are specified as named metadata::
  86. !dx.version = !{ !0 }
  87. !0 = !{ i32 <major>, i32 <minor> }
  88. DXIL version must be declared exactly once per LLVM module (translation unit) and is valid for the entire module.
  89. DXIL will evolve in a manner that retains backward compatibility.
  90. LLVM Bitcode version
  91. --------------------
  92. The current version of DXIL is based on LLVM bitcode v3.7. This encoding is necessarily implied by something outside the DXIL module.
  93. General Issues
  94. ==============
  95. An important goal is to enable HLSL to be closer to a strict subset of C/C++. This has implications for DXIL design and future hardware feature requests outlined below.
  96. Terminology
  97. -----------
  98. Resource refers to one of the following:
  99. * SRV - shader resource view (read-only)
  100. * UAV - unordered access view (read-write)
  101. * CBV - constant buffer view (read-only)
  102. * Sampler
  103. Intrinsics typically refer to operations missing in the core LLVM IR. DXIL represents HLSL built-in functions (also called intrinsics) not as LLVM intrinsics, but rather as external function calls.
  104. DXIL abstraction level
  105. ----------------------
  106. DXIL has level of abstraction similar to a 'scalarized' DXBC. DXIL is lower level IR than DXIR emitted by the front-end to be amenable to fast and robust JIT-ing in driver compilers.
  107. In particular, the following passes are performed to lower the HLSL/DXIR abstractions down to DXIL:
  108. * optimize function parameter copies
  109. * inline functions
  110. * allocate and transform shader signatures
  111. * lower matrices, optimizing intermediate storage
  112. * linearize multi-dimensional arrays and user-defined type accesses
  113. * scalarize vectors
  114. Scalar IR
  115. ---------
  116. DXIL operations work with scalar quantities. Several scalar quantities may be grouped together in a struct to represent several return values, which is used for memory operations, e.g., load/store, sample, etc., that benefit from access coalescing.
  117. Metadata, resource declarations, and debugging info may contain vectors to more closely convey source code shape to tools and debuggers.
  118. Future versions of IR may contain vectors or grouping hints for less-than-32-bit quantities, such as half and i16.
  119. Memory accesses
  120. ---------------
  121. DXIL conceptually aligns with DXBC in how different memory types are accessed. Out-of-bounds behavior and various restrictions are preserved.
  122. Indexable thread-local and groupshared variables are represented as variables and accessed via LLVM C-like pointers.
  123. Swizzled resources, such as textures, have opaque memory layouts from a DXIL point of view. Accesses to these resources are done via intrinsics.
  124. There are two layouts for constant buffer memory: (1) legacy, matching DXBC's layout and (2) linear layout. SM6 DXIL uses intrinsics to read cbuffer for either layout.
  125. Shader signatures require packing and are located in a special type of memory that cannot be viewed as linear. Accesses to signature values are done via special intrinsics in DXIL. If a signature parameter needs to be passed to a function, a copy is created first in threadlocal memory and the copy is passed to the function.
  126. Typed buffers represent memory with in-flight data conversion. Typed buffer load/store/atomics are done via special functions in DXIL with element-granularity indexing.
  127. The following pointer types are supported:
  128. * Non-indexable thread-local variables.
  129. * Indexable thread-local variables (DXBC x-registers).
  130. * Groupshared variables (DXBC g-registers).
  131. * Device memory pointer.
  132. * Constant-buffer-like memory pointer.
  133. The type of DXIL pointer is differentiated by LLVM addrspace construct. The HLSL compiler will make the best effort to infer the exact pointer addrspace such that a driver compiler can issue the most efficient instruction.
  134. A pointer can come into being in a number of ways:
  135. * Global Variables.
  136. * AllocaInst.
  137. * Synthesized as a result of some pointer arithmetic.
  138. DXIL uses 32-bit pointers in its representation.
  139. Out-of-bounds behavior
  140. ----------------------
  141. Indexable thread-local accesses are done via LLVM pointer and have C-like OOB semantics.
  142. Groupshared accesses are done via LLVM pointer too. The origin of a groupshared pointer must be a single TGSM allocation.
  143. If a groupshared pointer uses in-bound GEP instruction, it should not OOB. The behavior for an OOB access for in-bound pointer is undefined.
  144. For groupshared pointer from regular GEP, OOB will has same behavior as DXBC. Loads return 0 for OOB accesses; OOB stores are silently dropped.
  145. Resource accesses keeps the same out-of-bounds behavior as DXBC. Loads return 0 for OOB accesses; OOB stores are silently dropped.
  146. OOB pointer accesses in SM6.0 and later have undefined (C-like) behavior. LLVM memory optimization passes can be used to optimize such accesses. Where out-of-bound behavior is desired, intrinsic functions are used to access memory.
  147. Memory access granularity
  148. -------------------------
  149. Intrinsic and resource accesses may imply a wider access than requested by an instruction. DXIL defines memory accesses for i1, i16, i32, i64, f16, f32, f64 on thread local memory, and i32, f32, f64 for memory I/O (that is, groupshared memory and memory accessed via resources such as CBs, UAVs and SRVs).
  150. Number of virtual values
  151. ------------------------
  152. There is no limit on the number of virtual values in DXIL. The IR is guaranteed to be in an SSA form. For optimized shaders, the optimizer will run -mem2reg LLVM pass as well as perform other memory to register promotions if profitable.
  153. Control-flow restrictions
  154. -------------------------
  155. The DXIL control-flow graph must be reducible, as checked by T1-T2 test. DXIL does not preserve structured control flow of DXBC. Preserving structured control-flow property would impose significant burden on third-party tools optimizing to DXIL via LLVM, reducing appeal of DXIL.
  156. DXIL allows fall-through for switch label blocks. This is a difference from DXBC, in which the fall-through is prohibited.
  157. DXIL will not support the DXBC label and call instructions; LLVM functions can be used instead (see below). The primary uses for these are (1) HLSL interfaces, which are not supported, and (2) outlining of case-bodies in a switch statement annotated with [call], which is not a scenario of interest.
  158. Functions
  159. ---------
  160. Instead of DXBC labels/calls, DXIL supports functions and call instructions. Recursion is not allowed; DXIL validator enforces this.
  161. The functions are regular LLVM functions. Parameters can be passed by-value or by-reference. The functions are to facilitate separate compilation for big, complex shaders. However, driver compilers are free to inline functions as they see fit.
  162. Identifiers
  163. -----------
  164. DXIL identifiers must conform to LLVM IR identifier rules.
  165. Identifier mangling rules are the ones used by Clang 3.7 with the HLSL target.
  166. The following identifier prefixes are reserved:
  167. * dx.*, dxil.*, dxir.*
  168. * llvm.dx.*, llvm.dxil.*, llvm.dxir.*
  169. Address Width
  170. -------------
  171. DXIL will use only 32-bit addresses for pointers. Byte offsets are also 32-bit.
  172. Shader restrictions
  173. -------------------
  174. There is no support for the following in DXIL:
  175. * recursion
  176. * exceptions
  177. * indirect function calls and dynamic dispatch
  178. Entry points
  179. ------------
  180. The dx.entryPoints metadata specifies a list of entry point records, one for each entry point. Libraries could specify more than one entry point per module but currently exist outside the DXIL specification; the other shader models must specify exactly one entry point.
  181. For example::
  182. define void @"\01?myfunc1@@YAXXZ"() #0 { ... }
  183. define float @"\01?myfunc2@@YAMXZ"() #0 { ... }
  184. !dx.entryPoints = !{ !1, !2 }
  185. !1 = !{ void ()* @"\01?myfunc1@@YAXXZ", !"myfunc1", !3, null, null }
  186. !2 = !{ float ()* @"\01?myfunc2@@YAMXZ", !"myfunc2", !5, !6, !7 }
  187. Each entry point metadata record specifies:
  188. * reference to the entry point function global symbol
  189. * unmangled name
  190. * list of signatures
  191. * list of resources
  192. * list of tag-value pairs of shader capabilities and other properties
  193. A 'null' value specifies absence of a particular node.
  194. Shader capabilities are properties that are additional to properties dictated by shader model. The list is organized as pairs of i32 tag, followed immediately by the value itself.
  195. Hull shader representation
  196. --------------------------
  197. The hull shader is represented as two functions, related via metadata: (1) control point phase function, which is the entry point of the hull shader, and (2) patch constant phase function.
  198. For example::
  199. !dx.entryPoints = !{ !1 }
  200. !1 = !{ void ()* @"ControlPointFunc", ..., !2 } ; shader entry record
  201. !2 = !{ !"HS", !3 }
  202. !3 = !{ void ()* @"PatchConstFunc", ... } ; additional hull shader state
  203. The patch constant function represents original HLSL computation, and is not separated into fork and join phases, as it is the case in DXBC. The driver compiler may perform such separation if this is profitable for the target GPU.
  204. In DXBC to DXIL conversion, the original patch constant function cannot be recovered during DXBC-to-DXIL conversion. Instead, instructions of each fork and join phases are 'wrapped' by a loop that iterates the corresponding number of phase-instance-count iterations. Thus, fork/join instance ID becomes the loop induction variable. LoadPatchConstant intrinsic (see below) represents load from DXBC vpc register.
  205. The following table summarizes the names of intrinsic functions to load inputs and store outputs of hull and domain shaders. CP stands for Control Point, PC - for Patch Constant.
  206. =================== ==================== ====================== ======================
  207. Operation Control Point (Hull) Patch Constant Domain
  208. =================== ==================== ====================== ======================
  209. Store Input CP
  210. Load Input CP LoadInput LoadInput
  211. Store Output CP StoreOutput
  212. Load Output CP LoadOutputControlPoint LoadInput
  213. Store PC StorePatchConstant
  214. Load PC LoadPatchConstant LoadPatchConstant
  215. Store Output Vertex StoreOutput
  216. =================== ==================== ====================== ======================
  217. LoadPatchConstant function in PC stage is generated only by DXBC-to-DXIL converter, to access DXBC vpc registers. HLSL compiler produces IR that references LLVM IR values directly.
  218. Type System
  219. ===========
  220. Most of LLVM type system constructs are legal in DXIL.
  221. Primitive Types
  222. ---------------
  223. The following types are supported:
  224. * void
  225. * metadata
  226. * i1, i8, i16, i32, i64
  227. * half, float, double
  228. SM6.0 assumes native hardware support for i32 and float types.
  229. i8 is supported only in a few intrinsics to signify masks, enumeration constant values, or in metadata. It's not supported for memory access or computation by the shader.
  230. HLSL min12int, min16int and min16uint data types are mapped to i16.
  231. half and i16 are treated as corresponding DXBC min-presicion types (min16float, min16int/min16uint) in SM6.0.
  232. The HLSL compiler optimizer treats half, i16 and i8 data as data types natively supported by the hardware; i.e., saturation, range clipping, INF/NaN are done according to the IEEE standard. Such semantics allow the optimizer to reuse LLVM optimization passes.
  233. Hardware support for doubles in optional and is guarded by RequiresHardwareDouble CAP bit.
  234. Hardware support for i64 is optional and is guarded by a CAP bit.
  235. Vectors
  236. -------
  237. HLSL vectors are scalarized. They do not participate in computation; however, they may be present in declarations to convey original variable layout to tools, debuggers, and reflection.
  238. Future DXIL may add support for <2 x half> and <2 x i16> vectors or hints for packing related half and i16 quantities.
  239. Matrices
  240. --------
  241. Matrices are lowered to vectors, and are not referenced by instructions. They may be present in declarations to convey original variable layout to tools, debuggers, and reflection.
  242. Arrays
  243. ------
  244. Instructions may reference only 1D arrays of primitive types. However, complex arrays, e.g., multidimensional arrays or user-defined types, may be present to convey original variable layout to tools, debuggers, and reflection.
  245. User-defined types
  246. ------------------
  247. Original HLSL UDTs are lowered and are not referenced by instructions. However, they may be present in declarations to convey original variable layout to tools, debuggers, and reflection. Some resource operations return 'grouping' UDTs that group several return values; such UDTs are immediately 'decomposed' into components that are then consumed by other instructions.
  248. Type conversions
  249. ----------------
  250. Explicit conversions between types are supported via LLVM instructions.
  251. Precise qualifier
  252. -----------------
  253. HLSL precise type qualifier requires that all operations contributing to the value be IEEE compliant with respect to optimizations.
  254. Each relevant instruction that contributes to such a value is annotated with dx.precise metadata that indicates that it is illegal for the driver compiler to perform IEEE-unsafe optimizations.
  255. The default mode for DXIL is that operations are not precise; i.e., each operation is 'fast' (this is reverse of LLVM IR default mode). There is a way to change the default behavior for the entire shader via AllOperationsPrecise shader property.
  256. Type annotations
  257. ----------------
  258. User-defined types are annotated in DXIL to 'attach' additional properties to structure fields. For example, DXIL may contain type annotations for reflection purposes::
  259. ; namespace MyNamespace1
  260. ; {
  261. ; struct MyType1
  262. ; {
  263. ; float field1;
  264. ; int2 field2;
  265. ; };
  266. ; }
  267. %struct.MyNamespace1.MyType1 = type { float, <2 x i32> }
  268. !struct.MyNamespace1.MyType1 = !{ !1, !2 }
  269. !1 = !{ !"field1", null }
  270. !2 = !{ !"field2", null }
  271. ; struct MyType2
  272. ; {
  273. ; MyType1 array_field[2];
  274. ; float4 float4_field;
  275. ; };
  276. %struct.MyType2 = type { [2 x %struct.MyType1], <4 x float> }
  277. !struct.MyType2 = !{ !3, !4 }
  278. !3 = !{ !"array_field", null }
  279. !4 = !{ !"float4_field", null }
  280. The type/field annotation metadata hierarchy recursively mimics LLVM type hierarchy.
  281. Each field-annotation record has an optional named-value pair list for infrequent annotations and for future extensions. The lists are null in the example above.
  282. Note that Clang emits '::' to separate namespaces, if any, in type names. We modify Clang to use '.' instead, because it is illegal to use ':' in metadata names.
  283. Shader Properties and Capabilities
  284. ==================================
  285. Additional shader properties are specified via tag-value pair list, which is the last element in the entry function description record.
  286. Shader Flags
  287. ------------
  288. Shaders have additional flags that covey their capabilities via tag-value pair with tag kDxilShaderFlagsTag (0), followed by an i64 bitmask integer. The bits have the following meaning:
  289. === =====================================================================
  290. Bit Description
  291. === =====================================================================
  292. 0 Disable shader optimizations
  293. 1 Disable math refactoring
  294. 2 Shader uses doubles
  295. 3 Force early depth stencil
  296. 4 Enable raw and structured buffers
  297. 5 Shader uses min-precision, expressed as half and i16
  298. 6 Shader uses double extension intrinsics
  299. 7 Shader uses MSAD
  300. 8 All resources must be bound for the duration of shader execution
  301. 9 Enable view port and RT array index from any stage feeding rasterizer
  302. 10 Shader uses inner coverage
  303. 11 Shader uses stencil
  304. 12 Shader uses intrinsics that access tiled resources
  305. 13 Shader uses relaxed typed UAV load formats
  306. 14 Shader uses Level9 comparison filtering
  307. 15 Shader uses up to 64 UAVs
  308. 16 Shader uses UAVs
  309. 17 Shader uses CS4 raw and structured buffers
  310. 18 Shader uses Rasterizer Ordered Views
  311. 19 Shader uses wave intrinsics
  312. 20 Shader uses int64 instructions
  313. === =====================================================================
  314. Geometry Shader
  315. ---------------
  316. Geometry shader properties are specified via tag-value pair with tag kDxilGSStateTag (1), followed by a list of GS properties. The format of this list is the following.
  317. === ==== ===============================================================
  318. Idx Type Description
  319. === ==== ===============================================================
  320. 0 i32 Input primitive (InputPrimitive enum value).
  321. 1 i32 Max vertex count.
  322. 2 i32 Primitive topology for stream 0 (PrimitiveTopology enum value).
  323. 3 i32 Primitive topology for stream 1 (PrimitiveTopology enum value).
  324. 4 i32 Primitive topology for stream 2 (PrimitiveTopology enum value).
  325. 5 i32 Primitive topology for stream 3 (PrimitiveTopology enum value).
  326. === ==== ===============================================================
  327. Domain Shader
  328. -------------
  329. Domain shader properties are specified via tag-value pair with tag kDxilDSStateTag (2), followed by a list of DS properties. The format of this list is the following.
  330. === ==== ===============================================================
  331. Idx Type Description
  332. === ==== ===============================================================
  333. 0 i32 Tessellator domain (TessellatorDomain enum value).
  334. 1 i32 Input control point count.
  335. === ==== ===============================================================
  336. Hull Shader
  337. -----------
  338. Hull shader properties are specified via tag-value pair with tag kDxilHSStateTag (3), followed by a list of HS properties. The format of this list is the following.
  339. === ======= =====================================================================
  340. Idx Type Description
  341. === ======= =====================================================================
  342. 0 MDValue Patch constant function (global symbol).
  343. 1 i32 Input control point count.
  344. 2 i32 Output control point count.
  345. 3 i32 Tessellator domain (TessellatorDomain enum value).
  346. 4 i32 Tessellator partitioning (TessellatorPartitioning enum value).
  347. 5 i32 Tessellator output primitive (TessellatorOutputPrimitive enum value).
  348. 6 float Max tessellation factor.
  349. === ======= =====================================================================
  350. Compute Shader
  351. --------------
  352. Compute shader has the following tag-value properties.
  353. ===================== ======================== =============================================
  354. Tag Value Description
  355. ===================== ======================== =============================================
  356. kDxilNumThreadsTag(4) MD list: (i32, i32, i32) Number of threads (X,Y,Z) for compute shader.
  357. ===================== ======================== =============================================
  358. Shader Parameters and Signatures
  359. ================================
  360. This section formalizes how HLSL shader input and output parameters are expressed in DXIL.
  361. HLSL signatures and semantics
  362. -----------------------------
  363. Formal parameters of a shader entry function in HLSL specify how the shader interacts with the graphics pipeline. Input parameters, referred to as an input signature, specify values received by the shader. Output parameters, referred to as an output signature, specify values produced by the shader. The shader compiler maps HLSL input and output signatures into DXIL specifications that conform to hardware constraints outlined in the Direct3D Functional Specification. DXIL specifications are also called signatures.
  364. Signature mapping is a complex process, as there are many constraints. All signature parameters must fit into a finite space of N 4x32-bit registers. For efficiency reasons, parameters are packed together in a way that does not violate specification constraints. The process is called signature packing. Most signatures are tightly packed; however, the VS input signature is not packed, as the values are coming from the Input Assembler (IA) stage rather than the graphics pipeline. Alternately, the PS output signature is allocated to align the SV_Target semantic index with the output register index.
  365. Each HLSL signature parameter is defined via C-like type, interpolation mode, and semantic name and index. The type defines parameter shape, which may be quite complex. Interpolation mode adds to the packing constraints, namely that parameters packed together must have compatible interpolation modes. Semantics are extra names associated with parameters for the following purposes: (1) to specify whether a parameter is as a special System Value (SV) or not, (2) to link parameters to IA or StreamOut API streams, and (3) to aid debugging. Semantic index is used to disambiguate parameters that use the same semantic name, or span multiple rows of the register space.
  366. SV semantics add specific meanings and constraints to associated parameters. A parameter may be supplied by the hardware, and is then known as a System Generated Value (SGV). Alternatively, a parameter may be interpreted by the hardware and is then known as System Interpreted Value (SIV). SGVs and SIVs are pipeline-stage dependent; moreover, some participate in signature packing and some do not. Non-SV semantics always participate in signature packing.
  367. Most System Generated Values (SGV) are loaded using special Dxil intrinsic functions, rather than loading the input from a signature. These usually will not be present in the signature at all. Their presence may be detected by the declaration and use of the special instrinsic function itself. The exceptions to this are notible. In one case they are present and loaded from the signature instead of a special intrinsic because they must be part of the packed signature potentially passed from the prior stage, allowing the prior stage to override these values, such as for SV_PrimitiveID and SV_IsFrontFace that may be written in the the Geometry Shader. In another case, they identify signature elements that still contribute to DXBC signature for informational purposes, but will only use the special intrinsic function to read the value, such as for SV_PrimitiveID for GS input and SampleIndex for PS input.
  368. The classification of behavior for various system values in various signature locations is described in a table organized by SemanticKind and SigPointKind. The SigPointKind is a new classification that uniquely identifies each set of parameters that may be input or output for each entry point. For each combination of SemanticKind and SigPointKind, there is a SemanticInterpretationKind that defines the class of treatment for that location.
  369. Each SigPointKind also has a corresponding element allocation (or packing) behavior called PackingKind. Some SigPointKinds do not result in a signature at all, which corresponds to the packing kind of PackingKind::None.
  370. Signature Points are enumerated as follows in the SigPointKind
  371. .. <py>import hctdb_instrhelp</py>
  372. .. <py::lines('SIGPOINT-RST')>hctdb_instrhelp.get_sigpoint_rst()</py>
  373. .. SIGPOINT-RST:BEGIN
  374. == ======== ======= ========== ============== ============= ============================================================================
  375. ID SigPoint Related ShaderKind PackingKind SignatureKind Description
  376. == ======== ======= ========== ============== ============= ============================================================================
  377. 0 VSIn Invalid Vertex InputAssembler Input Ordinary Vertex Shader input from Input Assembler
  378. 1 VSOut Invalid Vertex Vertex Output Ordinary Vertex Shader output that may feed Rasterizer
  379. 2 PCIn HSCPIn Hull None Invalid Patch Constant function non-patch inputs
  380. 3 HSIn HSCPIn Hull None Invalid Hull Shader function non-patch inputs
  381. 4 HSCPIn Invalid Hull Vertex Input Hull Shader patch inputs - Control Points
  382. 5 HSCPOut Invalid Hull Vertex Output Hull Shader function output - Control Point
  383. 6 PCOut Invalid Hull PatchConstant PatchConstant Patch Constant function output - Patch Constant data passed to Domain Shader
  384. 7 DSIn Invalid Domain PatchConstant PatchConstant Domain Shader regular input - Patch Constant data plus system values
  385. 8 DSCPIn Invalid Domain Vertex Input Domain Shader patch input - Control Points
  386. 9 DSOut Invalid Domain Vertex Output Domain Shader output - vertex data that may feed Rasterizer
  387. 10 GSVIn Invalid Geometry Vertex Input Geometry Shader vertex input - qualified with primitive type
  388. 11 GSIn GSVIn Geometry None Invalid Geometry Shader non-vertex inputs (system values)
  389. 12 GSOut Invalid Geometry Vertex Output Geometry Shader output - vertex data that may feed Rasterizer
  390. 13 PSIn Invalid Pixel Vertex Input Pixel Shader input
  391. 14 PSOut Invalid Pixel Target Output Pixel Shader output
  392. 15 CSIn Invalid Compute None Invalid Compute Shader input
  393. == ======== ======= ========== ============== ============= ============================================================================
  394. .. SIGPOINT-RST:END
  395. Semantic Interpretations are as follows (SemanticInterpretationKind)
  396. .. <py>import hctdb_instrhelp</py>
  397. .. <py::lines('SEMINT-RST')>hctdb_instrhelp.get_sem_interpretation_enum_rst()</py>
  398. .. SEMINT-RST:BEGIN
  399. == ========== =============================================================
  400. ID Name Description
  401. == ========== =============================================================
  402. 0 NA Not Available
  403. 1 SV Normal System Value
  404. 2 SGV System Generated Value (sorted last)
  405. 3 Arb Treated as Arbitrary
  406. 4 NotInSig Not included in signature (intrinsic access)
  407. 5 NotPacked Included in signature, but does not contribute to packing
  408. 6 Target Special handling for SV_Target
  409. 7 TessFactor Special handling for tessellation factors
  410. 8 Shadow Shadow element must be added to a signature for compatibility
  411. == ========== =============================================================
  412. .. SEMINT-RST:END
  413. Semantic Interpretations for each SemanticKind at each SigPointKind are as follows
  414. .. <py>import hctdb_instrhelp</py>
  415. .. <py::lines('SEMINT-TABLE-RST')>hctdb_instrhelp.get_sem_interpretation_table_rst()</py>
  416. .. SEMINT-TABLE-RST:BEGIN
  417. ====================== ============ ===== ============ ============ ====== ======= ========== ============ ====== ===== ===== ============ ===== ============= ============= ========
  418. Semantic VSIn VSOut PCIn HSIn HSCPIn HSCPOut PCOut DSIn DSCPIn DSOut GSVIn GSIn GSOut PSIn PSOut CSIn
  419. ====================== ============ ===== ============ ============ ====== ======= ========== ============ ====== ===== ===== ============ ===== ============= ============= ========
  420. Arbitrary Arb Arb NA NA Arb Arb Arb Arb Arb Arb Arb NA Arb Arb NA NA
  421. VertexID SV NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
  422. InstanceID SV Arb NA NA Arb Arb NA NA Arb Arb Arb NA Arb Arb NA NA
  423. Position Arb SV NA NA SV SV Arb Arb SV SV SV NA SV SV NA NA
  424. RenderTargetArrayIndex Arb SV NA NA SV SV Arb Arb SV SV SV NA SV SV NA NA
  425. ViewPortArrayIndex Arb SV NA NA SV SV Arb Arb SV SV SV NA SV SV NA NA
  426. ClipDistance Arb SV NA NA SV SV Arb Arb SV SV SV NA SV SV NA NA
  427. CullDistance Arb SV NA NA SV SV Arb Arb SV SV SV NA SV SV NA NA
  428. OutputControlPointID NA NA NA NotInSig NA NA NA NA NA NA NA NA NA NA NA NA
  429. DomainLocation NA NA NA NA NA NA NA NotInSig NA NA NA NA NA NA NA NA
  430. PrimitiveID NA NA NotInSig NotInSig NA NA NA NotInSig NA NA NA Shadow SGV SGV NA NA
  431. GSInstanceID NA NA NA NA NA NA NA NA NA NA NA NotInSig NA NA NA NA
  432. SampleIndex NA NA NA NA NA NA NA NA NA NA NA NA NA Shadow _41 NA NA
  433. IsFrontFace NA NA NA NA NA NA NA NA NA NA NA NA SGV SGV NA NA
  434. Coverage NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig _50 NotPacked _41 NA
  435. InnerCoverage NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig _50 NA NA
  436. Target NA NA NA NA NA NA NA NA NA NA NA NA NA NA Target NA
  437. Depth NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotPacked NA
  438. DepthLessEqual NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotPacked _50 NA
  439. DepthGreaterEqual NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotPacked _50 NA
  440. StencilRef NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotPacked _50 NA
  441. DispatchThreadID NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig
  442. GroupID NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig
  443. GroupIndex NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig
  444. GroupThreadID NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NotInSig
  445. TessFactor NA NA NA NA NA NA TessFactor TessFactor NA NA NA NA NA NA NA NA
  446. InsideTessFactor NA NA NA NA NA NA TessFactor TessFactor NA NA NA NA NA NA NA NA
  447. ViewID NotInSig _61 NA NotInSig _61 NotInSig _61 NA NA NA NotInSig _61 NA NA NA NotInSig _61 NA NotInSig _61 NA NA
  448. Barycentrics NA NA NA NA NA NA NA NA NA NA NA NA NA NotPacked _61 NA NA
  449. ====================== ============ ===== ============ ============ ====== ======= ========== ============ ====== ===== ===== ============ ===== ============= ============= ========
  450. .. SEMINT-TABLE-RST:END
  451. Below is a vertex shader example that is used for illustration throughout this section::
  452. struct Foo {
  453. float a;
  454. float b[2];
  455. };
  456. struct VSIn {
  457. uint vid : SV_VertexID;
  458. float3 pos : Position;
  459. Foo foo[3] : SemIn1;
  460. float f : SemIn10;
  461. };
  462. struct VSOut
  463. {
  464. float f : SemOut1;
  465. Foo foo[3] : SemOut2;
  466. float4 pos : SV_Position;
  467. };
  468. void main(in VSIn In, // input signature
  469. out VSOut Out) // output signature
  470. {
  471. ...
  472. }
  473. Signature packing must be efficient. It should use as few registers as possible, and the packing algorithm should run in reasonable time. The complication is that the problem is NP complete, and the algorithm needs to resort to using a heuristic.
  474. While the details of the packing algorithm are not important at the moment, it is important to outline some concepts related to how a packed signature is represented in DXIL. Packing is further complicated by the complexity of parameter shapes induced by the C/C++ type system. In the example above, fields of Out.foo array field are actually arrays themselves, strided in memory. Allocating such strided shapes efficiently is hard. To simplify packing, the first step is to break user-defined (struct) parameters into constituent components and to make strided arrays contiguous. This preparation step enables the algorithm to operate on dense rectangular shapes, which we call signature elements. The output signature in the example above has the following elements: float Out_f, float Out_foo_a[3], float Out_foo_b[2][3], and float4 pos. Each element is characterized by the number of rows and columns. These are 1x1, 3x1, 6x1, and 1x4, respectively. The packing algorithm reduces to fitting these elements into Nx4 register space, satisfying all packing-compatibility constraints.
  475. Signature element record
  476. ------------------------
  477. Each signature element is represented in DXIL as a metadata record.
  478. For above example output signature, the element records are as follows::
  479. ; element ID, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  480. !20 = !{i32 6, !"SemOut", i8 0, i8 0, !40, i8 2, i32 1, i8 1, i32 1, i8 2, null}
  481. !21 = !{i32 7, !"SemOut", i8 0, i8 0, !41, i8 2, i32 3, i8 1, i32 1, i8 1, null}
  482. !22 = !{i32 8, !"SemOut", i8 0, i8 0, !42, i8 2, i32 6, i8 1, i32 1, i8 0, null}
  483. !23 = !{i32 9, !"SV_Position", i8 0, i8 3, !43, i8 2, i32 1, i8 4, i32 0, i8 0, null}
  484. A record contains the following fields.
  485. === =============== ===============================================================================
  486. Idx Type Description
  487. === =============== ===============================================================================
  488. 0 i32 Unique signature element record ID, used to identify the element in operations.
  489. 1 String metadata Semantic name.
  490. 2 i8 ComponentType (enum value).
  491. 3 i8 SemanticKind (enum value).
  492. 4 Metadata Metadata list that enumerates all semantic indexes of the flattened parameter.
  493. 5 i8 InterpolationMode (enum value).
  494. 6 i32 Number of element rows.
  495. 7 i8 Number of element columns.
  496. 8 i32 Starting row of element packing location.
  497. 9 i8 Starting column of element packing location.
  498. 10 Metadata Metadata list of additional tag-value pairs; can be 'null' or empty.
  499. === =============== ===============================================================================
  500. Semantic name system values always start with 'S', 'V', '_' , and it is illegal to start a user semantic with this prefix. Non-SVs can be ignored by drivers. Debug layers may use these to help validate signature compatibility between stages.
  501. The last metadata list is used to specify additional properties and future extensions.
  502. Signature record metadata
  503. -------------------------
  504. A shader typically has two signatures: input and output, while domain shader has an additional patch constant signature. The signatures are composed of signature element records and are attached to the shader entry metadata. The examples below clarify metadata details.
  505. Vertex shader HLSL
  506. ~~~~~~~~~~~~~~~~~~
  507. Here is the HLSL of the above vertex shader. The semantic index assignment is explained in section below::
  508. struct Foo
  509. {
  510. float a;
  511. float b[2];
  512. };
  513. struct VSIn
  514. {
  515. uint vid : SV_VertexID;
  516. float3 pos : Position;
  517. Foo foo[3] : SemIn1;
  518. // semantic index assignment:
  519. // foo[0].a : SemIn1
  520. // foo[0].b[0] : SemIn2
  521. // foo[0].b[1] : SemIn3
  522. // foo[1].a : SemIn4
  523. // foo[1].b[0] : SemIn5
  524. // foo[1].b[1] : SemIn6
  525. // foo[2].a : SemIn7
  526. // foo[2].b[0] : SemIn8
  527. // foo[2].b[1] : SemIn9
  528. float f : SemIn10;
  529. };
  530. struct VSOut
  531. {
  532. float f : SemOut1;
  533. Foo foo[3] : SemOut2;
  534. // semantic index assignment:
  535. // foo[0].a : SemOut2
  536. // foo[0].b[0] : SemOut3
  537. // foo[0].b[1] : SemOut4
  538. // foo[1].a : SemOut5
  539. // foo[1].b[0] : SemOut6
  540. // foo[1].b[1] : SemOut7
  541. // foo[2].a : SemOut8
  542. // foo[2].b[0] : SemOut9
  543. // foo[2].b[1] : SemOut10
  544. float4 pos : SV_Position;
  545. };
  546. void main(in VSIn In, // input signature
  547. out VSOut Out) // output signature
  548. {
  549. ...
  550. }
  551. The input signature is packed to be compatible with the IA stage. A packing algorithm must assign the following starting positions to the input signature elements:
  552. =================== ==== ======= ========= ===========
  553. Input element Rows Columns Start row Start column
  554. =================== ==== ======= ========= ===========
  555. uint VSIn.vid 1 1 0 0
  556. float3 VSIn.pos 1 3 1 0
  557. float VSIn.foo.a[3] 3 1 2 0
  558. float VSIn.foo.b[6] 6 1 5 0
  559. float VSIn.f 1 1 11 0
  560. =================== ==== ======= ========= ===========
  561. A reasonable packing algorithm would assign the following starting positions to the output signature elements:
  562. ==================== ==== ======= ========= ===========
  563. Input element Rows Columns Start row Start column
  564. ==================== ==== ======= ========= ===========
  565. uint VSOut.f 1 1 1 2
  566. float VSOut.foo.a[3] 3 1 1 1
  567. float VSOut.foo.b[6] 6 1 1 0
  568. float VSOut.pos 1 4 0 0
  569. ==================== ==== ======= ========= ===========
  570. Semantic index assignment
  571. ~~~~~~~~~~~~~~~~~~~~~~~~~
  572. Semantic index assignment in DXIL is exactly the same as for DXBC. Semantic index assignment, abbreviated s.idx above, is a consecutive enumeration of all fields under the same semantic name as if the signature were packed for the IA stage. That is, given a complex signature element, e.g., VSOut's foo[3] with semantic name SemOut and starting index 2, the element is flattened into individual fields: foo[0].a, foo[0].b[0], ..., foo[2].b[1], and the fields receive consecutive semantic indexes 2, 3, ..., 10, respectively. Semantic-index pairs are used to set up the IA stage and to capture values of individual signature registers via the StreamOut API.
  573. DXIL for VS signatures
  574. ~~~~~~~~~~~~~~~~~~~~~~
  575. The corresponding DXIL metadata is presented below::
  576. !dx.entryPoints = !{ !1 }
  577. !1 = !{ void @main(), !"main", !2, null, null }
  578. ; Signatures: In, Out, Patch Constant (optional)
  579. !2 = !{ !3, !4, null }
  580. ; Input signature (packed accordiong to IA rules)
  581. !3 = !{ !10, !11, !12, !13, !14 }
  582. ; element idx, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  583. !10 = !{i32 1, !"SV_VertexID", i8 0, i8 1, !30, i32 0, i32 1, i8 1, i32 0, i8 0, null}
  584. !11 = !{i32 2, !"Position", i8 0, i8 0, !30, i32 0, i32 1, i8 3, i32 1, i8 0, null}
  585. !12 = !{i32 3, !"SemIn", i8 0, i8 0, !32, i32 0, i32 3, i8 1, i32 2, i8 0, null}
  586. !13 = !{i32 4, !"SemIn", i8 0, i8 0, !33, i32 0, i32 6, i8 1, i32 5, i8 0, null}
  587. !14 = !{i32 5, !"SemIn", i8 0, i8 0, !34, i32 0, i32 1, i8 1, i32 11, i8 0, null}
  588. ; semantic index assignment:
  589. !30 = !{ i32 0 }
  590. !32 = !{ i32 1, i32 4, i32 7 }
  591. !33 = !{ i32 2, i32 3, i32 5, i32 6, i32 8, i32 9 }
  592. !34 = !{ i32 10 }
  593. ; Output signature (tightly packed according to pipeline stage packing rules)
  594. !4 = !{ !20, !21, !22, !23 }
  595. ; element ID, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  596. !20 = !{i32 6, !"SemOut", i8 0, i8 0, !40, i32 2, i32 1, i8 1, i32 1, i8 2, null}
  597. !21 = !{i32 7, !"SemOut", i8 0, i8 0, !41, i32 2, i32 3, i8 1, i32 1, i8 1, null}
  598. !22 = !{i32 8, !"SemOut", i8 0, i8 0, !42, i32 2, i32 6, i8 1, i32 1, i8 0, null}
  599. !23 = !{i32 9, !"SV_Position", i8 0, i8 3, !43, i32 2, i32 1, i8 4, i32 0, i8 0, null}
  600. ; semantic index assignment:
  601. !40 = !{ i32 1 }
  602. !41 = !{ i32 2, i32 5, i32 8 }
  603. !42 = !{ i32 3, i32 4, i32 6, i32 7, i32 9, i32 10 }
  604. !43 = !{ i32 0 }
  605. Hull shader example
  606. ~~~~~~~~~~~~~~~~~~~
  607. A hull shader (HS) is defined by two entry point functions: control point (CP) function to compute control points, and patch constant (PC) function to compute patch constant data, including the tessellation factors. The inputs to both functions are the input control points for an entire patch, and therefore each element may be indexed by row and, in addition, is indexed by vertex.
  608. Here is an HS example entry point metadata and signature list::
  609. ; !105 is extended parameter list containing reference to HS State:
  610. !101 = !{ void @HSMain(), !"HSMain", !102, null, !105 }
  611. ; Signatures: In, Out, Patch Constant
  612. !102 = !{ !103, !104, !204 }
  613. The entry point record specifies: (1) CP function HSMain as the main symbol, and (2) PC function via optional metadata node !105.
  614. CP-input signature describing one input control point::
  615. !103 = !{ !110, !111 }
  616. ; element ID, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  617. !110= !{i32 1, !"SV_Position", i8 0, i8 3, !130, i32 0, i32 1, i8 4, i32 0, i8 0, null}
  618. !111= !{i32 2, !"array", i8 0, i8 0, !131, i32 0, i32 4, i8 3, i32 1, i8 0, null}
  619. ; semantic indexing for flattened elements:
  620. !130 = !{ i32 0 }
  621. !131 = !{ i32 0, i32 1, i32 2, i32 3 }
  622. Note that SV_OutputControlPointID and SV_PrimitiveID input elements are SGVs loaded through special Dxil intrinsics, and are not present in the signature at all. These have a semantic interpretation of SemanticInterpretationKind::NotInSig.
  623. CP-output signature describing one output control point::
  624. !104 = !{ !120, !121 }
  625. ; element ID, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  626. !120= !{i32 3, !"SV_Position", i8 0, i8 3, !130, i32 0, i32 1, i8 4, i32 0, i8 0, null}
  627. !121= !{i32 4, !"array", i8 0, i8 0, !131, i32 0, i32 4, i8 3, i32 1, i8 0, null}
  628. Hull shaders require an extended parameter that defines extra state::
  629. ; extended parameter HS State
  630. !105 = !{ i32 3, !201 }
  631. ; HS State record defines patch constant function and other properties
  632. ; Patch Constant Function, in CP count, out CP count, tess domain, tess part, out prim, max tess factor
  633. !201 = !{ void @PCMain(), 4, 4, 3, 1, 3, 16.0 }
  634. PC-output signature::
  635. !204 = !{ !220, !221, !222 }
  636. ; element ID, semantic name, etype, sv, s.idx, interp, rows, cols, start row, col, ext. list
  637. !220= !{i32 3, !"SV_TessFactor", i8 0, i8 25, !130, i32 0, i32 4, i8 1, i32 0, i8 3, null}
  638. !221= !{i32 4, !"SV_InsideTessFactor", i8 0, i8 26, !231, i32 0, i32 2, i8 1, i32 4, i8 3, null}
  639. !222= !{i32 5, !"array", i8 0, i8 0, !131, i32 0, i32 4, i8 3, i32 0, i8 0, null}
  640. ; semantic indexing for flattened elements:
  641. !231 = !{ i32 0, i32 1 }
  642. Accessing signature value in operations
  643. ---------------------------------------
  644. There are no function parameters or variables that correspond to signature elements. Instead loadInput and storeOutput functions are used to access signature element values in operations. The accesses are scalar.
  645. These are the operation signatures::
  646. ; overloads: SM5.1: f16|f32|i16|i32, SM6.0: f16|f32|f64|i8|i16|i32|i64
  647. declare float @dx.op.loadInput.f32(
  648. i32, ; opcode
  649. i32, ; input ID
  650. i32, ; row (relative to start row of input ID)
  651. i8, ; column (relative to start column of input ID), constant in [0,3]
  652. i32) ; vertex index
  653. ; overloads: SM5.1: f16|f32|i16|i32, SM6.0: f16|f32|f64|i8|i16|i32|i64
  654. declare void @dx.op.storeOutput.f32(
  655. i32, ; opcode
  656. i32, ; output ID
  657. i32, ; row (relative to start row of output ID)
  658. i8, ; column (relative to start column of output ID), constant in [0,3]
  659. float) ; value to store
  660. LoadInput/storeOutput takes input/output element ID, which is the unique ID of a signature element metadata record. The row parameter is the array element row index from the start of the element; the register index is obtained by adding the start row of the element and the row parameter value. Similarly, the column parameter is relative column index; the packed register component is obtained by adding the start component of the element (packed col) and the column value. Several overloads exist to access elements of different primitive types. LoadInput takes an additional vertex index parameter that represents vertex index for DS CP-inputs and GS inputs; vertex index must be undef in other cases.
  661. Signature packing
  662. -----------------
  663. Signature elements must be packed into a space of N 4-32-bit registers according to runtime constraints. DXIL contains packed signatures. The packing algorithm is more aggressive than that for DX11. However, DXIL packing is only a suggestion to the driver implementation. Driver compilers can rearrange signature elements as they see fit, while preserving compatibility of connected pipeline stages. DXIL is designed in such a way that it is easy to 'relocate' signature elements - loadInput/storeOutput row and column indices do not need to change since they are relative to the start row/column for each element.
  664. Signature packing types
  665. ~~~~~~~~~~~~~~~~~~~~~~~
  666. Two pipeline stages can connect in four different ways, resulting in four packing types.
  667. 1. Input Assembly: VS input only
  668. * Elements all map to unique registers, they may not be packed together.
  669. * Interpolation mode is not used.
  670. 2. Connects to Rasterizer: VS output, HS CP-input/output and PC-input, DS CP-input/output, GS input/output, PS input
  671. * Elements can be packed according to constraints.
  672. * Interpolation mode is used and must be consistent between connecting signatures.
  673. * While HS CP-output and DS CP-input signatures do not go through the rasterizer, they are still treated as such. The reason is the pass-through HS case, in which HS CP-input and HS CP-output must have identical packing for efficiency.
  674. 3. Patch Constant: HS PC-output, DS PC-input
  675. * SV_TessFactor and SV_InsideTessFactor are the only SVs relevant here, and this is the only location where they are legal. These have special packing considerations.
  676. * Interpolation mode is not used.
  677. 4. Pixel Shader Output: PS output only
  678. * Only SV_Target maps to output register space.
  679. * No packing is performed, semantic index corresponds to render target index.
  680. Packing constraints
  681. ~~~~~~~~~~~~~~~~~~~
  682. The packing algorithm is stricter and more aggressive in DXIL than in DXBC, although still compatible. In particular, array signature elements are not broken up into scalars, even if each array access can be disambiguated to a literal index. DXIL and DXBC signature packing are not identical, so linking them together into a single pipeline is not supported across compiler generations.
  683. The row dimension of a signature element represents an index range. If constraints permit, two adjacent or overlapping index ranges are coalesced into a single index range.
  684. Packing constraints are as follows:
  685. 1. A register must have only one interpolation mode for all 4 components.
  686. 2. Register components containing SVs must be to the right of components containing non-SVs.
  687. 3. SV_ClipDistance and SV_CullDistance have additional constraints:
  688. a. May be packed together
  689. b. Must occupy a maximum of 2 registers (8-components)
  690. c. SV_ClipDistance must have linear interpolation mode
  691. 4. Registers containing SVs may not be within an index range, with the exception of Tessellation Factors (TessFactors).
  692. 5. If an index range R1 overlaps with a TessFactor index range R2, R1 must be contained within R2. As a consequence, outside and inside TessFactors occupy disjoint index ranges when packed.
  693. 6. Non-TessFactor index ranges are combined into a larger range, if they overlap.
  694. 7. SGVs must be packed after all non-SGVs have been packed. If there are several SGVs, they are packed in the order of HLSL declaration.
  695. Packing for SGVs
  696. ~~~~~~~~~~~~~~~~
  697. Non-SGV portions of two connecting signatures must match; however, SGV portions don't have to. An example would be a PS declaring SV_PrimitiveID as an input. If VS connects to PS, PS's SV_PrimitiveID value is synthesized by hardware; moreover, it is illegal to output SV_PrimitiveID from a VS. If GS connects PS, GS may declare SV_PrimitiveID as its output.
  698. Unfortunately, SGV specification creates a complication for separate compilation of connecting shaders. For example, GS outputs SV_PrimitiveID, and PS inputs SV_IsFrontFace and SV_PrimitiveID in this order. The positions of SV_PrimitiveID are incompatible in GS and PS signatures. Not much can be done about this ambiguity in SM5.0 and earlier; the programmers will have to rely on SDKLayers to catch potential mismatch.
  699. SM5.1 and later shaders work on D3D12+ runtime that uses PSO objects to describe pipeline state. Therefore, a driver compiler has access to both connecting shaders during compilation, even though the HLSL compiler does not. The driver compiler can resolve SGV ambiguity in signatures easily. For SM5.1 and later, the HLSL compiler will ensure that declared SGVs fit into packed signature; however, it will set SGV's start row-column location to (-1, 0) such that the driver compiler must resolve SGV placement during PSO compilation.
  700. Shader Resources
  701. ================
  702. All global resources referenced by entry points of an LLVM module are described via named metadata dx.resources, which consists of four metadata lists of resource records::
  703. !dx.resources = !{ !1, !2, !3, !4 }
  704. Resource lists are as follows.
  705. === ======== ==============================
  706. Idx Type Description
  707. === ======== ==============================
  708. 0 Metadata SRVs - shader resource views.
  709. 1 Metadata UAVs - unordered access views.
  710. 2 Metadata CBVs - constant buffer views.
  711. 3 Metadata Samplers.
  712. === ======== ==============================
  713. Metadata resource records
  714. -------------------------
  715. Each resource list contains resource records. Each resource record contains fields that are common for each resource type, followed by fields specific to each resource type, followed by a metadata list of tag/value pairs, which can be used to specify additional properties or future extensions and may be null or empty.
  716. Common fields:
  717. === =============== ==========================================================================================
  718. Idx Type Description
  719. === =============== ==========================================================================================
  720. 0 i32 Unique resource record ID, used to identify the resource record in createHandle operation.
  721. 1 Pointer Pointer to a global constant symbol with the original shape of resource and element type.
  722. 2 Metadata string Name of resource variable.
  723. 3 i32 Bind space ID of the root signature range that corresponds to this resource.
  724. 4 i32 Bind lower bound of the root signature range that corresponds to this resource.
  725. 5 i32 Range size of the root signature range that corresponds to this resource.
  726. === =============== ==========================================================================================
  727. When the shader has reflection information, the name is the original, unmangled HLSL name. If reflection is stripped, the name is empty string.
  728. SRV-specific fields:
  729. === =============== ==========================================================================================
  730. Idx Type Description
  731. === =============== ==========================================================================================
  732. 6 i32 SRV resource shape (enum value).
  733. 7 i32 SRV sample count.
  734. 8 Metadata Metadata list of additional tag-value pairs.
  735. === =============== ==========================================================================================
  736. SRV-specific tag/value pairs:
  737. === === ==== =================================================== ============================================
  738. Idx Tag Type Resource Type Description
  739. === === ==== =================================================== ============================================
  740. 0 0 i32 Any resource, except RawBuffer and StructuredBuffer Element type.
  741. 1 1 i32 StructuredBuffer Element stride or StructureBuffer, in bytes.
  742. === === ==== =================================================== ============================================
  743. The symbol names for the are kDxilTypedBufferElementTypeTag (0) and kDxilStructuredBufferElementStrideTag (1).
  744. UAV-specific fields:
  745. === =============== ==========================================================================================
  746. Idx Type Description
  747. === =============== ==========================================================================================
  748. 6 i32 UAV resource shape (enum value).
  749. 7 i1 1 - globally-coherent UAV; 0 - otherwise.
  750. 8 i1 1 - UAV has counter; 0 - otherwise.
  751. 9 i1 1 - UAV is ROV (rasterizer ordered view); 0 - otherwise.
  752. 10 Metadata Metadata list of additional tag-value pairs.
  753. === =============== ==========================================================================================
  754. UAV-specific tag/value pairs:
  755. === === ==== ====================================================== ============================================
  756. Idx Tag Type Resource Type Description
  757. === === ==== ====================================================== ============================================
  758. 0 0 i32 RW resource, except RWRawBuffer and RWStructuredBuffer Element type.
  759. 1 1 i32 RWStructuredBuffer Element stride or StructureBuffer, in bytes.
  760. === === ==== ====================================================== ============================================
  761. The symbol names for the are kDxilTypedBufferElementTypeTag (0) and kDxilStructuredBufferElementStrideTag (1).
  762. CBV-specific fields:
  763. === =============== ==========================================================================================
  764. Idx Type Description
  765. === =============== ==========================================================================================
  766. 6 i32 Constant buffer size in bytes.
  767. 7 Metadata Metadata list of additional tag-value pairs.
  768. === =============== ==========================================================================================
  769. Sampler-specific fields:
  770. === =============== ==========================================================================================
  771. Idx Type Description
  772. === =============== ==========================================================================================
  773. 6 i32 Sampler type (enum value).
  774. 7 Metadata Metadata list of additional tag-value pairs.
  775. === =============== ==========================================================================================
  776. The following example demonstrates SRV metadata::
  777. ; Original HLSL
  778. ; Texture2D<float4> MyTexture2D : register(t0, space0);
  779. ; StructuredBuffer<NS1::MyType1> MyBuffer[2][3] : register(t1, space0);
  780. !1 = !{ !2, !3 }
  781. ; Scalar resource: Texture2D<float4> MyTexture2D.
  782. %dx.types.ResElem.v4f32 = type { <4 x float> }
  783. @MyTexture2D = external addrspace(1) constant %dx.types.ResElem.v4f32, align 16
  784. !2 = !{ i32 0, %dx.types.ResElem.v4f32 addrspace(1)* @MyTexture2D, !"MyTexture2D",
  785. i32 0, i32 0, i32 1, i32 2, i32 0, null }
  786. ; Array resource: StructuredBuffer<MyType1> MyBuffer[2][3].
  787. %struct.NS1.MyType1 = type { float, <2 x i32> }
  788. %dx.types.ResElem.NS1.MyType1 = type { %struct.NS1.MyType1 }
  789. @MyBuffer = external addrspace(1) constant [2x [3 x %dx.types.ResElem.NS1.MyType1]], align 16
  790. !3 = !{ i32 1, [2 x [3 x %dx.types.ResElem.NS1.MyType1]] addrspace(1)* @MyBuffer, !"MyBuffer",
  791. i32 0, i32 1, i32 6, i32 11, i32 0, null }
  792. The type name of the variable is constructed by appending the element name (primitive, vector or UDT name) to dx.types.ResElem prefix. The type configuration of the resource range variable conveys (1) resource range shape and (2) resource element type.
  793. Reflection information
  794. ----------------------
  795. Resource reflection data is conveyed via the resource's metadata record and global, external variable. The metadata record contains the original HLSL name, root signature range information, and the reference to the global resource variable declaration. The resource variable declaration conveys resource range shape, resource type and resource element type.
  796. The following disassembly provides an example::
  797. ; Scalar resource: Texture2D<float4> MyTexture2D.
  798. %dx.types.ResElem.v4f32 = type { <4 x float> }
  799. @MyTexture2D = external addrspace(1) constant %dx.types.ResElem.v4f32, align 16
  800. !0 = !{ i32 0, %dx.types.ResElem.v4f32 addrspace(1)* @MyTexture2D, !"MyTexture2D",
  801. i32 0, i32 3, i32 1, i32 2, i32 0, null }
  802. ; struct MyType2 { float4 field1; int2 field2; };
  803. ; Constant buffer: ConstantBuffer<MyType2> MyCBuffer1[][3] : register(b5, space7)
  804. %struct.MyType2 = type { <4 x float>, <2 x i32> }
  805. ; Type reflection information (optional)
  806. !struct.MyType2 = !{ !1, !2 }
  807. !1 = !{ !"field1", null }
  808. !2 = !{ !"field2", null }
  809. %dx.types.ResElem.MyType1 = type { %struct.MyType2 }
  810. @MyCBuffer1 = external addrspace(1) constant [0 x [3 x %dx.types.ResElem.MyType2]], align 16
  811. !3 = !{ i32 0, [0 x [3 x %dx.types.ResElem.MyType1]] addrspace(1)* @MyCBuffer1, !"MyCBuffer1",
  812. i32 7, i32 5, i32 -1, null }
  813. The reflection information can be removed from DXIL by obfuscating the resource HLSL name and resource variable name as well as removing reflection type annotations, if any.
  814. Structure of resource operation
  815. -------------------------------
  816. Operations involving shader resources and samplers are expressed via external function calls.
  817. Below is an example for the sample method::
  818. %dx.types.ResRet.f32 = type { float, float, float, float, i32 }
  819. declare %dx.types.ResRet.f32 @dx.op.sample.f32(
  820. i32, ; opcode
  821. %dx.types.ResHandle, ; texture handle
  822. %dx.types.SamplerHandle, ; sampler handle
  823. float, ; coordinate c0
  824. float, ; coordinate c1
  825. float, ; coordinate c2
  826. float, ; coordinate c3
  827. i32, ; offset o0
  828. i32, ; offset o1
  829. i32, ; offset o2
  830. float) ; clamp
  831. The method always returns five scalar values that are aggregated in dx.types.ResRet.f32 type and extracted into scalars via LLVM's extractelement right after the call. The first four elements are sample values and the last field is the status of operation for tiled resources. Some return values may be unused, which is easily determined from the SSA form. The driver compiler is free to specialize the sample instruction to the most efficient form depending on which return values are used in computation.
  832. If applicable, each intrinsic is overloaded on return type, e.g.::
  833. %dx.types.ResRet.f32 = type { float, float, float, float, i32 }
  834. %dx.types.ResRet.f16 = type { half, half, half, half, i32 }
  835. declare %dx.types.ResRet.f32 @dx.op.sample.f32(...)
  836. declare %dx.types.ResRet.f16 @dx.op.sample.f16(...)
  837. Wherever applicable, the return type indicates the "precision" at which the operation is executed. For example, sample intrinsic that returns half data is allowed to be executed at half precision, assuming hardware supports this; however, if the return type is float, the sample operation must be executed in float precision. If lower-precision is not supported by hardware, it is allowed to execute a higher-precision variant of the operation.
  838. The opcode parameter uniquely identifies the sample operation. More details can be found in the Instructions section. The value of opcode is the same for all overloads of an operation.
  839. Some resource operations are "polymorphic" with respect to resource types, e.g., dx.op.sample.f32 operates on several resource types: Texture1D[Array], Texture2D[Array], Texture3D, TextureCUBE[Array].
  840. Each resource/sampler is represented by a pair of i32 values. The first value is a unique (virtual) resource range ID, which corresponds to HLSL declaration of a resource/sampler. Range ID must be a constant for SM5.1 and below. The second integer is a 0-based index within the range. The index must be constant for SM5.0 and below.
  841. Both indices can be dynamic for SM6 and later to provide flexibility in usage of resources/samplers in control flow, e.g.::
  842. Texture2D<float4> a[8], b[8];
  843. ...
  844. Texture2D<float4> c;
  845. if(cond) // arbitrary expression
  846. c = a[idx1];
  847. else
  848. c = b[idx2];
  849. ... = c.Sample(...);
  850. Resources/samplers used in such a way must reside in descriptor tables (cannot be root descriptors); this will be validated during shader and root signature setup.
  851. The DXIL verifier will ensure that all leaf-ranges (a and b above) of such a resource/sampler live-range have the same resource/sampler type and element type. If applicable, this constraint may be relaxed in the future. In particular, it is logical from HLSL programmer point of view to issue loads on compatible resource types, e.g., Texture2D, RWTexture2D, ROVTexture2D::
  852. Texture2D<float4> a[8];
  853. RWTexture2D<float4> b[6];
  854. ...
  855. Texture2D<float4> c;
  856. if(cond) // arbitrary expression
  857. c = a[idx1];
  858. else
  859. c = b[idx2];
  860. ... = c.Load(...);
  861. LLVM's undef value is used for unused input parameters. For example, coordinates c2 and c3 in an dx.op.sample.f32 call for Texture2D are undef, as only two coordinates c0 and c1 are required.
  862. If the clamp parameter is unused, its default value is 0.0f.
  863. Resource operations are not overloaded on input parameter types. For example, dx.op.sample.f32 operation does not have an overload where coordinates have half, rather than float, data type. Instead, the precision of input arguments can be inferred from the IR via a straightforward lookup along an SSA edge, e.g.::
  864. %c0 = fpext half %0 to float
  865. %res = call %dx.types.ResRet.f32 @dx.op.sample.f32(..., %c0, ...)
  866. SSA form makes it easy to infer that value %0 of type half got promoted to float. The driver compiler can tailor the instruction to the most efficient form for the target hardware.
  867. Resource operations
  868. -------------------
  869. The section lists resource access operations. The specification is given for float return type, if applicable. The list of all overloads can be found in the appendix on intrinsic operations.
  870. Some general rules to interpret resource operations:
  871. * The number of active (meaningful) return components is determined by resource element type. Other return values must be unused; validator ensures this.
  872. * GPU instruction needs status only if the status return value is used in the program, which is determined through SSA.
  873. * Overload suffixes are specified for each resource operation.
  874. * Type of resource determines which inputs must be defined. Unused inputs are passed typed LLVM 'undef' values. This is checked by the DXIL validator.
  875. * Offset input parameters are i8 constants in [-8,+7] range; default offset is 0.
  876. Resource operation return types
  877. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  878. Many resource operations return several scalar values as well as status for tiled resource access. The return values are grouped into a helper structure type, as this is LLVM's way to return several values from the operation. After an operation, helper types are immediately decomposed into scalars, which are used in further computation.
  879. The defined helper types are listed below::
  880. %dx.types.ResRet.i8 = type { i8, i8, i8, i8, i32 }
  881. %dx.types.ResRet.i16 = type { i16, i16, i16, i16, i32 }
  882. %dx.types.ResRet.i32 = type { i32, i32, i32, i32, i32 }
  883. %dx.types.ResRet.i64 = type { i64, i64, i64, i64, i32 }
  884. %dx.types.ResRet.f16 = type { half, half, half, half, i32 }
  885. %dx.types.ResRet.f32 = type { float, float, float, float, i32 }
  886. %dx.types.ResRet.f64 = type { double, double, double, double, i32 }
  887. %dx.types.Dimensions = type { i32, i32, i32, i32 }
  888. %dx.types.SamplePos = type { float, float }
  889. Resource handles
  890. ~~~~~~~~~~~~~~~~
  891. Resources are identified via handles passed to resource operations. Handles are represented via opaque type::
  892. %dx.types.Handle = type { i8 * }
  893. The handles are created out of resource range ID and index into the range::
  894. declare %dx.types.Handle @dx.op.createHandle(
  895. i32, ; opcode
  896. i8, ; resource class: SRV=0, UAV=1, CBV=2, Sampler=3
  897. i32, ; resource range ID (constant)
  898. i32, ; index into the range
  899. i1) ; non-uniform resource index: false or true
  900. Resource class is a constant that indicates which metadata list (SRV, UAV, CBV, Sampler) to use for property queries.
  901. Resource range ID is an i32 constant, which is the position of the metadata record in the corresponding metadata list. Range IDs start with 0 and are contiguous within each list.
  902. Index is an i32 value that may be a constant or a value computed by the shader.
  903. CBufferLoadLegacy
  904. ~~~~~~~~~~~~~~~~~
  905. The following signature shows the operation syntax::
  906. ; overloads: SM5.1: f32|i32|f64, future SM: possibly deprecated
  907. %dx.types.CBufRet.f32 = type { float, float, float, float }
  908. declare %dx.types.CBufRet.f32 @dx.op.cbufferLoadLegacy.f32(
  909. i32, ; opcode
  910. %dx.types.Handle, ; resource handle
  911. i32) ; 0-based row index (row = 16-byte DXBC register)
  912. Valid resource types: ConstantBuffer. Valid shader model: SM5.1 and earlier.
  913. The operation loads four 32-bit values from a constant buffer, which has legacy, 16-byte layout. Values are extracted via "extractvalue" instruction; unused values may be optimized away by the driver compiler. The operation respects SM5.1 and earlier OOB behavior for cbuffers.
  914. CBufferLoad
  915. ~~~~~~~~~~~
  916. The following signature shows the operation syntax::
  917. ; overloads: SM5.1: f32|i32|f64, SM6.0: f16|f32|f64|i16|i32|i64
  918. declare float @dx.op.cbufferLoad.f32(
  919. i32, ; opcode
  920. %dx.types.Handle, ; resource handle
  921. i32, ; byte offset from the start of the buffer memory
  922. i32) ; read alignment
  923. Valid resource types: ConstantBuffer.
  924. The operation loads a value from a constant buffer, which has linear layout, using 1D index: byte offset from the beginning of the buffer memory. The operation respects SM5.1 and earlier OOB behavior for cbuffers.
  925. Read alignment is a constant value identifying what the byte offset alignment is. If the actual byte offset does not have this alignment, the results of this operation are undefined.
  926. GetDimensions
  927. ~~~~~~~~~~~~~
  928. The following signature shows the operation syntax::
  929. declare %dx.types.Dimensions @dx.op.getDimensions(
  930. i32, ; opcode
  931. %dx.types.Handle, ; resource handle
  932. i32) ; MIP level
  933. This table describes the return component meanings for each resource type { c0, c1, c2, c3 }.
  934. ==================== ===== ========== ========== ==========
  935. Valid resource types c0 c1 c2 c3
  936. ==================== ===== ========== ========== ==========
  937. [RW]Texture1D width undef undef MIP levels
  938. [RW]Texture1DArray width array size undef MIP levels
  939. [RW]Texture2D width height undef MIP levels
  940. [RW]Texture2DArray width height array size MIP levels
  941. [RW]Texture3D width height depth MIP levels
  942. [RW]Texture2DMS width height undef samples
  943. [RW]Texture2DMSArray width height array size samples
  944. TextureCUBE width height undef MIP levels
  945. TextureCUBEArray width height array size MIP levels
  946. [RW]TypedBuffer width undef undef undef
  947. [RW]RawBuffer width undef undef undef
  948. [RW]StructuredBuffer width undef undef undef
  949. ==================== ===== ========== ========== ==========
  950. MIP levels is always undef for RW resources. Undef means the component will not be used. The validator will verify this.
  951. There is no GetDimensions that returns float values.
  952. Sample
  953. ~~~~~~
  954. The following signature shows the operation syntax::
  955. ; overloads: SM5.1: f32, SM6.0: f16|f32
  956. declare %dx.types.ResRet.f32 @dx.op.sample.f32(
  957. i32, ; opcode
  958. %dx.types.Handle, ; texture handle
  959. %dx.types.Handle, ; sampler handle
  960. float, ; coordinate c0
  961. float, ; coordinate c1
  962. float, ; coordinate c2
  963. float, ; coordinate c3
  964. i32, ; offset o0
  965. i32, ; offset o1
  966. i32, ; offset o2
  967. float) ; clamp
  968. =================== ================================ ===================
  969. Valid resource type # of active coordinates # of active offsets
  970. =================== ================================ ===================
  971. Texture1D 1 (c0) 1 (o0)
  972. Texture1DArray 2 (c0, c1 = array slice) 1 (o0)
  973. Texture2D 2 (c0, c1) 2 (o0, o1)
  974. Texture2DArray 3 (c0, c1, c2 = array slice) 2 (o0, o1)
  975. Texture3D 3 (c0, c1, c2) 3 (o0, o1, o2)
  976. TextureCUBE 3 (c0, c1, c2) 3 (o0, o1, o2)
  977. TextureCUBEArray 4 (c0, c1, c2, c3 = array slice) 3 (o0, o1, o2)
  978. =================== ================================ ===================
  979. SampleBias
  980. ~~~~~~~~~~
  981. The following signature shows the operation syntax::
  982. ; overloads: SM5.1: f32, SM6.0: f16|f32
  983. declare %dx.types.ResRet.f32 @dx.op.sampleBias.f32(
  984. i32, ; opcode
  985. %dx.types.Handle, ; texture handle
  986. %dx.types.Handle, ; sampler handle
  987. float, ; coordinate c0
  988. float, ; coordinate c1
  989. float, ; coordinate c2
  990. float, ; coordinate c3
  991. i32, ; offset o0
  992. i32, ; offset o1
  993. i32, ; offset o2
  994. float, ; bias: in [-16.f,15.99f]
  995. float) ; clamp
  996. Valid resource types and active components/offsets are the same as for the sample operation.
  997. SampleLevel
  998. ~~~~~~~~~~~
  999. The following signature shows the operation syntax::
  1000. ; overloads: SM5.1: f32, SM6.0: f16|f32
  1001. declare %dx.types.ResRet.f32 @dx.op.sampleLevel.f32(
  1002. i32, ; opcode
  1003. %dx.types.Handle, ; texture handle
  1004. %dx.types.Handle, ; sampler handle
  1005. float, ; coordinate c0
  1006. float, ; coordinate c1
  1007. float, ; coordinate c2
  1008. float, ; coordinate c3
  1009. i32, ; offset o0
  1010. i32, ; offset o1
  1011. i32, ; offset o2
  1012. float) ; LOD
  1013. Valid resource types and active components/offsets are the same as for the sample operation.
  1014. SampleGrad
  1015. ~~~~~~~~~~
  1016. The following signature shows the operation syntax::
  1017. ; overloads: SM5.1: f32, SM6.0: f16|f32
  1018. declare %dx.types.ResRet.f32 @dx.op.sampleGrad.f32(
  1019. i32, ; opcode
  1020. %dx.types.Handle, ; texture handle
  1021. %dx.types.Handle, ; sampler handle
  1022. float, ; coordinate c0
  1023. float, ; coordinate c1
  1024. float, ; coordinate c2
  1025. float, ; coordinate c3
  1026. i32, ; offset o0
  1027. i32, ; offset o1
  1028. i32, ; offset o2
  1029. float, ; ddx0
  1030. float, ; ddx1
  1031. float, ; ddx2
  1032. float, ; ddy0
  1033. float, ; ddy1
  1034. float, ; ddy2
  1035. float) ; clamp
  1036. Valid resource types and active components and offsets are the same as for the sample operation. Valid active ddx and ddy are the same as offsets.
  1037. SampleCmp
  1038. ~~~~~~~~~
  1039. The following signature shows the operation syntax::
  1040. ; overloads: SM5.1: f32, SM6.0: f16|f32
  1041. declare %dx.types.ResRet.f32 @dx.op.sampleCmp.f32(
  1042. i32, ; opcode
  1043. %dx.types.Handle, ; texture handle
  1044. %dx.types.Handle, ; sampler handle
  1045. float, ; coordinate c0
  1046. float, ; coordinate c1
  1047. float, ; coordinate c2
  1048. float, ; coordinate c3
  1049. i32, ; offset o0
  1050. i32, ; offset o1
  1051. i32, ; offset o2
  1052. float, ; compare value
  1053. float) ; clamp
  1054. =================== ================================ ===================
  1055. Valid resource type # of active coordinates # of active offsets
  1056. =================== ================================ ===================
  1057. Texture1D 1 (c0) 1 (o0)
  1058. Texture1DArray 2 (c0, c1 = array slice) 1 (o0)
  1059. Texture2D 2 (c0, c1) 2 (o0, o1)
  1060. Texture2DArray 3 (c0, c1, c2 = array slice) 2 (o0, o1)
  1061. TextureCUBE 3 (c0, c1, c2) 3 (o0, o1, o2)
  1062. TextureCUBEArray 4 (c0, c1, c2, c3 = array slice) 3 (o0, o1, o2)
  1063. =================== ================================ ===================
  1064. SampleCmpLevelZero
  1065. ~~~~~~~~~~~~~~~~~~
  1066. The following signature shows the operation syntax::
  1067. ; overloads: SM5.1: f32, SM6.0: f16|f32
  1068. declare %dx.types.ResRet.f32 @dx.op.sampleCmpLevelZero.f32(
  1069. i32, ; opcode
  1070. %dx.types.Handle, ; texture handle
  1071. %dx.types.Handle, ; sampler handle
  1072. float, ; coordinate c0
  1073. float, ; coordinate c1
  1074. float, ; coordinate c2
  1075. float, ; coordinate c3
  1076. i32, ; offset o0
  1077. i32, ; offset o1
  1078. i32, ; offset o2
  1079. float) ; compare value
  1080. Valid resource types and active components/offsets are the same as for the sampleCmp operation.
  1081. TextureLoad
  1082. ~~~~~~~~~~~
  1083. The following signature shows the operation syntax::
  1084. ; overloads: SM5.1: f32|i32, SM6.0: f16|f32|i16|i32
  1085. declare %dx.types.ResRet.f32 @dx.op.textureLoad.f32(
  1086. i32, ; opcode
  1087. %dx.types.Handle, ; texture handle
  1088. i32, ; MIP level; sample for Texture2DMS
  1089. i32, ; coordinate c0
  1090. i32, ; coordinate c1
  1091. i32, ; coordinate c2
  1092. i32, ; offset o0
  1093. i32, ; offset o1
  1094. i32) ; offset o2
  1095. =================== ========= ============================ ===================
  1096. Valid resource type MIP level # of active coordinates # of active offsets
  1097. =================== ========= ============================ ===================
  1098. Texture1D yes 1 (c0) 1 (o0)
  1099. RWTexture1D undef 1 (c0) undef
  1100. Texture1DArray yes 2 (c0, c1 = array slice) 1 (o0)
  1101. RWTexture1DArray undef 2 (c0, c1 = array slice) undef
  1102. Texture2D yes 2 (c0, c1) 2 (o0, o1)
  1103. RWTexture2D undef 2 (c0, c1) undef
  1104. Texture2DArray yes 3 (c0, c1, c2 = array slice) 2 (o0, o1)
  1105. RWTexture2DArray undef 3 (c0, c1, c2 = array slice) undef
  1106. Texture3D yes 3 (c0, c1, c2) 3 (o0, o1, o2)
  1107. RWTexture3D undef 3 (c0, c1, c2) undef
  1108. =================== ========= ============================ ===================
  1109. For Texture2DMS:
  1110. =================== ============ =================================
  1111. Valid resource type Sample index # of active coordinate components
  1112. =================== ============ =================================
  1113. Texture2DMS yes 2 (c0, c1)
  1114. Texture2DMSArray yes 3 (c0, c1, c2 = array slice)
  1115. =================== ============ =================================
  1116. TextureStore
  1117. ~~~~~~~~~~~~
  1118. The following signature shows the operation syntax::
  1119. ; overloads: SM5.1: f32|i32, SM6.0: f16|f32|i16|i32
  1120. ; returns: status
  1121. declare void @dx.op.textureStore.f32(
  1122. i32, ; opcode
  1123. %dx.types.Handle, ; texture handle
  1124. i32, ; coordinate c0
  1125. i32, ; coordinate c1
  1126. i32, ; coordinate c2
  1127. float, ; value v0
  1128. float, ; value v1
  1129. float, ; value v2
  1130. float, ; value v3
  1131. i8) ; write mask
  1132. The write mask indicates which components are written (x - 1, y - 2, z - 4, w - 8), similar to DXBC. The mask must cover all resource components.
  1133. =================== =================================
  1134. Valid resource type # of active coordinate components
  1135. =================== =================================
  1136. RWTexture1D 1 (c0)
  1137. RWTexture1DArray 2 (c0, c1 = array slice)
  1138. RWTexture2D 2 (c0, c1)
  1139. RWTexture2DArray 3 (c0, c1, c2 = array slice)
  1140. RWTexture3D 3 (c0, c1, c2)
  1141. =================== =================================
  1142. CalculateLOD
  1143. ~~~~~~~~~~~~
  1144. The following signature shows the operation syntax::
  1145. ; returns: LOD
  1146. declare float @dx.op.calculateLOD.f32(
  1147. i32, ; opcode
  1148. %dx.types.Handle, ; texture handle
  1149. %dx.types.Handle, ; sampler handle
  1150. float, ; coordinate c0, [0.0, 1.0]
  1151. float, ; coordinate c1, [0.0, 1.0]
  1152. float, ; coordinate c2, [0.0, 1.0]
  1153. i1) ; true - clamped; false - unclamped
  1154. ============================= =======================
  1155. Valid resource type # of active coordinates
  1156. ============================= =======================
  1157. Texture1D, Texture1DArray 1 (c0)
  1158. Texture2D, Texture2DArray 2 (c0, c1)
  1159. Texture3D 3 (c0, c1, c2)
  1160. TextureCUBE, TextureCUBEArray 3 (c0, c1, c2)
  1161. ============================= =======================
  1162. TextureGather
  1163. ~~~~~~~~~~~~~
  1164. The following signature shows the operation syntax::
  1165. ; overloads: SM5.1: f32|i32, SM6.0: f16|f32|i16|i32
  1166. declare %dx.types.ResRet.f32 @dx.op.textureGather.f32(
  1167. i32, ; opcode
  1168. %dx.types.Handle, ; texture handle
  1169. %dx.types.Handle, ; sampler handle
  1170. float, ; coordinate c0
  1171. float, ; coordinate c1
  1172. float, ; coordinate c2
  1173. float, ; coordinate c3
  1174. i32, ; offset o0
  1175. i32, ; offset o1
  1176. i32) ; channel, constant in {0=red,1=green,2=blue,3=alpha}
  1177. =================== ================================ ===================
  1178. Valid resource type # of active coordinates # of active offsets
  1179. =================== ================================ ===================
  1180. Texture2D 2 (c0, c1) 2 (o0, o1)
  1181. Texture2DArray 3 (c0, c1, c2 = array slice) 2 (o0, o1)
  1182. TextureCUBE 3 (c0, c1, c2) 0
  1183. TextureCUBEArray 4 (c0, c1, c2, c3 = array slice) 0
  1184. =================== ================================ ===================
  1185. TextureGatherCmp
  1186. ~~~~~~~~~~~~~~~~
  1187. The following signature shows the operation syntax::
  1188. ; overloads: SM5.1: f32|i32, SM6.0: f16|f32|i16|i32
  1189. declare %dx.types.ResRet.f32 @dx.op.textureGatherCmp.f32(
  1190. i32, ; opcode
  1191. %dx.types.Handle, ; texture handle
  1192. %dx.types.Handle, ; sampler handle
  1193. float, ; coordinate c0
  1194. float, ; coordinate c1
  1195. float, ; coordinate c2
  1196. float, ; coordinate c3
  1197. i32, ; offset o0
  1198. i32, ; offset o1
  1199. i32, ; channel, constant in {0=red,1=green,2=blue,3=alpha}
  1200. float) ; compare value
  1201. Valid resource types and active components/offsets are the same as for the textureGather operation.
  1202. Texture2DMSGetSamplePosition
  1203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1204. The following signature shows the operation syntax::
  1205. declare %dx.types.SamplePos @dx.op.texture2DMSGetSamplePosition(
  1206. i32, ; opcode
  1207. %dx.types.Handle, ; texture handle
  1208. i32) ; sample ID
  1209. Returns sample position of a texture.
  1210. RenderTargetGetSamplePosition
  1211. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1212. The following signature shows the operation syntax::
  1213. declare %dx.types.SamplePos @dx.op.renderTargetGetSamplePosition(
  1214. i32, ; opcode
  1215. i32) ; sample ID
  1216. Returns sample position of a render target.
  1217. RenderTargetGetSampleCount
  1218. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1219. The following signature shows the operation syntax::
  1220. declare i32 @dx.op.renderTargetGetSampleCount(
  1221. i32) ; opcode
  1222. Returns sample count of a render target.
  1223. BufferLoad
  1224. ~~~~~~~~~~
  1225. The following signature shows the operation syntax::
  1226. ; overloads: SM5.1: f32|i32, SM6.0: f32|i32
  1227. declare %dx.types.ResRet.f32 @dx.op.bufferLoad.f32(
  1228. i32, ; opcode
  1229. %dx.types.Handle, ; resource handle
  1230. i32, ; coordinate c0
  1231. i32) ; coordinate c1
  1232. The call respects SM5.1 OOB and alignment rules.
  1233. =================== =====================================================
  1234. Valid resource type # of active coordinates
  1235. =================== =====================================================
  1236. [RW]TypedBuffer 1 (c0 in elements)
  1237. [RW]RawBuffer 1 (c0 in bytes)
  1238. [RW]TypedBuffer 2 (c0 in elements, c1 = byte offset into the element)
  1239. =================== =====================================================
  1240. BufferStore
  1241. ~~~~~~~~~~~
  1242. The following signature shows the operation syntax::
  1243. ; overloads: SM5.1: f32|i32, SM6.0: f32|i32
  1244. ; returns: status
  1245. declare void @dx.op.bufferStore.f32(
  1246. i32, ; opcode
  1247. %dx.types.Handle, ; resource handle
  1248. i32, ; coordinate c0
  1249. i32, ; coordinate c1
  1250. float, ; value v0
  1251. float, ; value v1
  1252. float, ; value v2
  1253. float, ; value v3
  1254. i8) ; write mask
  1255. The call respects SM5.1 OOB and alignment rules.
  1256. The write mask indicates which components are written (x - 1, y - 2, z - 4, w - 8), similar to DXBC. For RWTypedBuffer, the mask must cover all resource components. For RWRawBuffer and RWStructuredBuffer, valid masks are: x, xy, xyz, xyzw.
  1257. =================== =====================================================
  1258. Valid resource type # of active coordinates
  1259. =================== =====================================================
  1260. RWTypedBuffer 1 (c0 in elements)
  1261. RWRawBuffer 1 (c0 in bytes)
  1262. RWStructuredBuffer 2 (c0 in elements, c1 = byte offset into the element)
  1263. =================== =====================================================
  1264. BufferUpdateCounter
  1265. ~~~~~~~~~~~~~~~~~~~
  1266. The following signature shows the operation syntax::
  1267. ; opcodes: bufferUpdateCounter
  1268. declare void @dx.op.bufferUpdateCounter(
  1269. i32, ; opcode
  1270. %dx.types.ResHandle, ; buffer handle
  1271. i8) ; 1 - increment, -1 - decrement
  1272. Valid resource type: RWRawBuffer.
  1273. AtomicBinOp
  1274. ~~~~~~~~~~~
  1275. The following signature shows the operation syntax::
  1276. ; overloads: SM5.1: i32, SM6.0: i32
  1277. ; returns: original value in memory before the operation
  1278. declare i32 @dx.op.atomicBinOp.i32(
  1279. i32, ; opcode
  1280. %dx.types.Handle, ; resource handle
  1281. i32, ; binary operation code: EXCHANGE, IADD, AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
  1282. i32, ; coordinate c0
  1283. i32, ; coordinate c1
  1284. i32, ; coordinate c2
  1285. i32) ; new value
  1286. The call respects SM5.1 OOB and alignment rules.
  1287. =================== =====================================================
  1288. Valid resource type # of active coordinates
  1289. =================== =====================================================
  1290. RWTexture1D 1 (c0)
  1291. RWTexture1DArray 2 (c0, c1 = array slice)
  1292. RWTexture2D 2 (c0, c1)
  1293. RWTexture2DArray 3 (c0, c1, c2 = array slice)
  1294. RWTexture3D 3 (c0, c1, c2)
  1295. RWTypedBuffer 1 (c0 in elements)
  1296. RWRawBuffer 1 (c0 in bytes)
  1297. RWStructuredBuffer 2 (c0 in elements, c1 - byte offset into the element)
  1298. =================== =====================================================
  1299. AtomicBinOp subsumes corresponding DXBC atomic operations that do not return the old value in memory. The driver compiler is free to specialize the corresponding GPU instruction if the return value is unused.
  1300. AtomicCompareExchange
  1301. ~~~~~~~~~~~~~~~~~~~~~
  1302. The following signature shows the operation syntax::
  1303. ; overloads: SM5.1: i32, SM6.0: i32
  1304. ; returns: original value in memory before the operation
  1305. declare i32 @dx.op.atomicBinOp.i32(
  1306. i32, ; opcode
  1307. %dx.types.Handle, ; resource handle
  1308. i32, ; coordinate c0
  1309. i32, ; coordinate c1
  1310. i32, ; coordinate c2
  1311. i32, ; comparison value
  1312. i32) ; new value
  1313. The call respects SM5.1 OOB and alignment rules.
  1314. =================== =====================================================
  1315. Valid resource type # of active coordinates
  1316. =================== =====================================================
  1317. RWTexture1D 1 (c0)
  1318. RWTexture1DArray 2 (c0, c1 = array slice)
  1319. RWTexture2D 2 (c0, c1)
  1320. RWTexture2DArray 3 (c0, c1, c2 = array slice)
  1321. RWTexture3D 3 (c0, c1, c2)
  1322. RWTypedBuffer 1 (c0 in elements)
  1323. RWRawBuffer 1 (c0 in bytes)
  1324. RWStructuredBuffer 2 (c0 in elements, c1 - byte offset into the element)
  1325. =================== =====================================================
  1326. AtomicCompareExchange subsumes DXBC's atomic compare store. The driver compiler is free to specialize the corresponding GPU instruction if the return value is unused.
  1327. GetBufferBasePtr (SM6.0)
  1328. ~~~~~~~~~~~~~~~~~~~~~~~~
  1329. The following signature shows the operation syntax::
  1330. Returns i8* pointer to the base of [RW]RawBuffer instance.
  1331. declare i8 addrspace(ASmemory) * @dx.op.getBufferBasePtr.pASmemory (
  1332. i32, ; opcode
  1333. %dx.types.Handle) ; resource handle
  1334. Returns i8* pointer to the base of ConstantBuffer instance.
  1335. declare i8 addrspace(AScbuffer) * @dx.op.getBufferBasePtr.pAScbuffer(
  1336. i32, ; opcode
  1337. %dx.types.Handle) ; resource handle
  1338. Given SM5.1 resource handle, return base pointer to perform pointer-based accesses to the resource memory.
  1339. Note: the functionality is requested for SM6.0 to support pointer-based accesses to SM5.1 resources with raw linear memory (raw buffer and cbuffer) in HLSL next. This would be one of the way how a valid pointer is produced in the shader, and would let new-style, pointer-based code access SM5.1 resources with linear memory view.
  1340. Atomic operations via pointer
  1341. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1342. Groupshared memory atomic operations are done via LLVM atomic instructions atomicrmw and cmpxchg. The instructions accept only i32 addrspace(ASgs) * pointers, where ASgs is the addrspace number of groupshared variables. Atomicrmw instruction does not support 'sub' and 'nand' operations. These constraints may be revisited in the future. OOB behavior is undefined.
  1343. SM6.0 will enable similar mechanism for atomic operations performed on device memory (raw buffer).
  1344. Samplers
  1345. --------
  1346. There are no intrinsics for samplers. Sampler reflection data is represented similar to other resources.
  1347. Immediate Constant Buffer
  1348. -------------------------
  1349. There is no immediate constant buffer in DXIL. Instead, indexable constants are represented via LLVM global initialized constants in address space ASicb.
  1350. Texture Buffers
  1351. ---------------
  1352. A texture buffer is mapped to RawBuffer. Texture buffer variable declarations are present for reflection purposes only.
  1353. Groupshared memory
  1354. ------------------
  1355. Groupshared memory (DXBC g-registers) is linear in DXIL. Groupshared variables are declared via global variables in addrspace(ASgs). The optimizer will not group variables; the driver compiler can do this if desired. Accesses to groupshared variables occur via pointer load/store instructions (see below).
  1356. Indexable threadlocal memory
  1357. ----------------------------
  1358. Indexable threadlocal memory (DXBC x-registers) is linear in DXIL. Threadlocal variables are "declared" via alloca instructions. Threadlocal variables are assumed to reside in addrspace(0). The variables are not allocated into some memory pool; the driver compiler can do this, if desired. Accesses to threadlocal variables occur via pointer load/store instructions (see below).
  1359. Load/Store/Atomics via pointer in future SM
  1360. -------------------------------------------
  1361. HLSL offers several abstractions with linear memory: buffers, cbuffers, groupshared and indexable threadlocal memory, that are conceptually similar, but have different HLSL syntax and some differences in behavior, which are exposed to HLSL developers. The plan is to introduce pointers into HLSL to unify access syntax to such linear-memory resources such that they appear conceptually the same to HLSL programmers.
  1362. Each resource memory type is expressed by a unique LLVM address space. The following table shows memory types and their address spaces:
  1363. ========================================= =====================================
  1364. Memory type Address space number n - addrspace(n)
  1365. ========================================= =====================================
  1366. code, local, indexable threadlocal memory AS_default = 0
  1367. device memory ([RW]RawBuffer) AS_memory = 1
  1368. cbuffer-like memory (ConstantBuffer) AS_cbuffer = 2
  1369. groupshared memory AS_groupshared = 3
  1370. ========================================= =====================================
  1371. Pointers can be produced in the shader in a variety of ways (see Memory accesses section). Note that if GetBaseBufferPtr was used on [RW]RawBuffer or ConstantBuffer to produce a pointer, the base pointer is stateless; i.e., it "loses its connection" to the underlying resource and is treated as a stateless pointer into a particular memory type.
  1372. Additional resource properties
  1373. ------------------------------
  1374. TODO: enumerate all additional resource range properties, e.g., ROV, Texture2DMS, globally coherent, UAV counter, sampler mode, CB: immediate/dynamic indexed.
  1375. Operations
  1376. ==========
  1377. DXIL operations are represented in two ways: using LLVM instructions and using LLVM external functions. The reference list of operations as well as their overloads can be found in the attached Excel spreadsheet "DXIL Operations".
  1378. Operations via instructions
  1379. ---------------------------
  1380. DXIL uses a subset of core LLVM IR instructions that make sense for HLSL, where the meaning of the LLVM IR operation matches the meaning of the HLSL operation.
  1381. The following LLVM instructions are valid in a DXIL program, with the specified operand types where applicable. The legend for overload types (v)oid, (h)alf, (f)loat, (d)ouble, (1)-bit, (8)-bit, (w)ord, (i)nt, (l)ong.
  1382. .. <py>import hctdb_instrhelp</py>
  1383. .. <py::lines('INSTR-RST')>hctdb_instrhelp.get_instrs_rst()</py>
  1384. .. INSTR-RST:BEGIN
  1385. ============= ======================================================================= =================
  1386. Instruction Action Operand overloads
  1387. ============= ======================================================================= =================
  1388. Ret returns a value (possibly void), from a function. vhfd1wil
  1389. Br branches (conditional or unconditional)
  1390. Switch performs a multiway switch
  1391. Add returns the sum of its two operands wil
  1392. FAdd returns the sum of its two operands hfd
  1393. Sub returns the difference of its two operands wil
  1394. FSub returns the difference of its two operands hfd
  1395. Mul returns the product of its two operands wil
  1396. FMul returns the product of its two operands hfd
  1397. UDiv returns the quotient of its two unsigned operands wil
  1398. SDiv returns the quotient of its two signed operands wil
  1399. FDiv returns the quotient of its two operands hfd
  1400. URem returns the remainder from the unsigned division of its two operands wil
  1401. SRem returns the remainder from the signed division of its two operands wil
  1402. FRem returns the remainder from the division of its two operands hfd
  1403. Shl shifts left (logical) wil
  1404. LShr shifts right (logical), with zero bit fill wil
  1405. AShr shifts right (arithmetic), with 'a' operand sign bit fill wil
  1406. And returns a bitwise logical and of its two operands 1wil
  1407. Or returns a bitwise logical or of its two operands 1wil
  1408. Xor returns a bitwise logical xor of its two operands 1wil
  1409. Alloca allocates memory on the stack frame of the currently executing function
  1410. Load reads from memory
  1411. Store writes to memory
  1412. GetElementPtr gets the address of a subelement of an aggregate value
  1413. AtomicCmpXchg atomically modifies memory
  1414. AtomicRMW atomically modifies memory
  1415. Trunc truncates an integer 1wil
  1416. ZExt zero extends an integer 1wil
  1417. SExt sign extends an integer 1wil
  1418. FPToUI converts a floating point to UInt hfd1wil
  1419. FPToSI converts a floating point to SInt hfd1wil
  1420. UIToFP converts a UInt to floating point hfd1wil
  1421. SIToFP converts a SInt to floating point hfd1wil
  1422. FPTrunc truncates a floating point hfd
  1423. FPExt extends a floating point hfd
  1424. BitCast performs a bit-preserving type cast hfd1wil
  1425. AddrSpaceCast casts a value addrspace
  1426. ICmp compares integers 1wil
  1427. FCmp compares floating points hfd
  1428. PHI is a PHI node instruction
  1429. Call calls a function
  1430. Select selects an instruction
  1431. ExtractValue extracts from aggregate
  1432. ============= ======================================================================= =================
  1433. .. INSTR-RST:END
  1434. Operations via external functions
  1435. ---------------------------------
  1436. Operations missing in core LLVM IR, such as abs, fma, discard, etc., are represented by external functions, whose name is prefixed with dx.op.
  1437. The very first parameter of each such external function is the opcode of the operation, which is an i32 constant. For example, dx.op.unary computes a unary function T res = opcode(T input). Opcode defines which unary function to perform.
  1438. Opcodes are defined on a dense range and will be provided as enum in a header file. The opcode parameter is introduced for efficiency reasons: grouping of operations to reduce the total number of overloads and more efficient property lookup, e.g., via an array of operation properties rather than a hash table.
  1439. .. <py::lines('OPCODES-RST')>hctdb_instrhelp.get_opcodes_rst()</py>
  1440. .. OPCODES-RST:BEGIN
  1441. === ============================= =================================================================================================================
  1442. ID Name Description
  1443. === ============================= =================================================================================================================
  1444. 0 TempRegLoad_ Helper load operation
  1445. 1 TempRegStore_ Helper store operation
  1446. 2 MinPrecXRegLoad_ Helper load operation for minprecision
  1447. 3 MinPrecXRegStore_ Helper store operation for minprecision
  1448. 4 LoadInput_ Loads the value from shader input
  1449. 5 StoreOutput_ Stores the value to shader output
  1450. 6 FAbs_ returns the absolute value of the input value.
  1451. 7 Saturate_ clamps the result of a single or double precision floating point value to [0.0f...1.0f]
  1452. 8 IsNaN_ Returns true if x is NAN or QNAN, false otherwise.
  1453. 9 IsInf_ Returns true if x is +INF or -INF, false otherwise.
  1454. 10 IsFinite_ Returns true if x is finite, false otherwise.
  1455. 11 IsNormal_ returns IsNormal
  1456. 12 Cos_ returns cosine(theta) for theta in radians.
  1457. 13 Sin_ returns sine(theta) for theta in radians.
  1458. 14 Tan_ returns tan(theta) for theta in radians.
  1459. 15 Acos_ Returns the arccosine of the specified value. Input should be a floating-point value within the range of -1 to 1.
  1460. 16 Asin_ Returns the arccosine of the specified value. Input should be a floating-point value within the range of -1 to 1
  1461. 17 Atan_ Returns the arctangent of the specified value. The return value is within the range of -PI/2 to PI/2.
  1462. 18 Hcos_ returns the hyperbolic cosine of the specified value.
  1463. 19 Hsin_ returns the hyperbolic sine of the specified value.
  1464. 20 Htan_ returns the hyperbolic tangent of the specified value.
  1465. 21 Exp_ returns 2^exponent
  1466. 22 Frc_ extract fracitonal component.
  1467. 23 Log_ returns log base 2.
  1468. 24 Sqrt_ returns square root
  1469. 25 Rsqrt_ returns reciprocal square root (1 / sqrt(src)
  1470. 26 Round_ne_ floating-point round to integral float.
  1471. 27 Round_ni_ floating-point round to integral float.
  1472. 28 Round_pi_ floating-point round to integral float.
  1473. 29 Round_z_ floating-point round to integral float.
  1474. 30 Bfrev_ Reverses the order of the bits.
  1475. 31 Countbits_ Counts the number of bits in the input integer.
  1476. 32 FirstbitLo_ Returns the location of the first set bit starting from the lowest order bit and working upward.
  1477. 33 FirstbitHi_ Returns the location of the first set bit starting from the highest order bit and working downward.
  1478. 34 FirstbitSHi_ Returns the location of the first set bit from the highest order bit based on the sign.
  1479. 35 FMax_ returns a if a >= b, else b
  1480. 36 FMin_ returns a if a < b, else b
  1481. 37 IMax_ IMax(a,b) returns a if a > b, else b
  1482. 38 IMin_ IMin(a,b) returns a if a < b, else b
  1483. 39 UMax_ unsigned integer maximum. UMax(a,b) = a > b ? a : b
  1484. 40 UMin_ unsigned integer minimum. UMin(a,b) = a < b ? a : b
  1485. 41 IMul_ multiply of 32-bit operands to produce the correct full 64-bit result.
  1486. 42 UMul_ multiply of 32-bit operands to produce the correct full 64-bit result.
  1487. 43 UDiv_ unsigned divide of the 32-bit operand src0 by the 32-bit operand src1.
  1488. 44 UAddc_ unsigned add of 32-bit operand with the carry
  1489. 45 USubb_ unsigned subtract of 32-bit operands with the borrow
  1490. 46 FMad_ floating point multiply & add
  1491. 47 Fma_ fused multiply-add
  1492. 48 IMad_ Signed integer multiply & add
  1493. 49 UMad_ Unsigned integer multiply & add
  1494. 50 Msad_ masked Sum of Absolute Differences.
  1495. 51 Ibfe_ Integer bitfield extract
  1496. 52 Ubfe_ Unsigned integer bitfield extract
  1497. 53 Bfi_ Given a bit range from the LSB of a number, places that number of bits in another number at any offset
  1498. 54 Dot2_ Two-dimensional vector dot-product
  1499. 55 Dot3_ Three-dimensional vector dot-product
  1500. 56 Dot4_ Four-dimensional vector dot-product
  1501. 57 CreateHandle creates the handle to a resource
  1502. 58 CBufferLoad loads a value from a constant buffer resource
  1503. 59 CBufferLoadLegacy loads a value from a constant buffer resource
  1504. 60 Sample samples a texture
  1505. 61 SampleBias samples a texture after applying the input bias to the mipmap level
  1506. 62 SampleLevel samples a texture using a mipmap-level offset
  1507. 63 SampleGrad samples a texture using a gradient to influence the way the sample location is calculated
  1508. 64 SampleCmp samples a texture and compares a single component against the specified comparison value
  1509. 65 SampleCmpLevelZero samples a texture and compares a single component against the specified comparison value
  1510. 66 TextureLoad reads texel data without any filtering or sampling
  1511. 67 TextureStore reads texel data without any filtering or sampling
  1512. 68 BufferLoad reads from a TypedBuffer
  1513. 69 BufferStore writes to a RWTypedBuffer
  1514. 70 BufferUpdateCounter atomically increments/decrements the hidden 32-bit counter stored with a Count or Append UAV
  1515. 71 CheckAccessFullyMapped determines whether all values from a Sample, Gather, or Load operation accessed mapped tiles in a tiled resource
  1516. 72 GetDimensions gets texture size information
  1517. 73 TextureGather gathers the four texels that would be used in a bi-linear filtering operation
  1518. 74 TextureGatherCmp same as TextureGather, except this instrution performs comparison on texels, similar to SampleCmp
  1519. 75 Texture2DMSGetSamplePosition gets the position of the specified sample
  1520. 76 RenderTargetGetSamplePosition gets the position of the specified sample
  1521. 77 RenderTargetGetSampleCount gets the number of samples for a render target
  1522. 78 AtomicBinOp performs an atomic operation on two operands
  1523. 79 AtomicCompareExchange atomic compare and exchange to memory
  1524. 80 Barrier inserts a memory barrier in the shader
  1525. 81 CalculateLOD calculates the level of detail
  1526. 82 Discard discard the current pixel
  1527. 83 DerivCoarseX_ computes the rate of change per stamp in x direction.
  1528. 84 DerivCoarseY_ computes the rate of change per stamp in y direction.
  1529. 85 DerivFineX_ computes the rate of change per pixel in x direction.
  1530. 86 DerivFineY_ computes the rate of change per pixel in y direction.
  1531. 87 EvalSnapped evaluates an input attribute at pixel center with an offset
  1532. 88 EvalSampleIndex evaluates an input attribute at a sample location
  1533. 89 EvalCentroid evaluates an input attribute at pixel center
  1534. 90 SampleIndex returns the sample index in a sample-frequency pixel shader
  1535. 91 Coverage returns the coverage mask input in a pixel shader
  1536. 92 InnerCoverage returns underestimated coverage input from conservative rasterization in a pixel shader
  1537. 93 ThreadId reads the thread ID
  1538. 94 GroupId reads the group ID (SV_GroupID)
  1539. 95 ThreadIdInGroup reads the thread ID within the group (SV_GroupThreadID)
  1540. 96 FlattenedThreadIdInGroup provides a flattened index for a given thread within a given group (SV_GroupIndex)
  1541. 97 EmitStream emits a vertex to a given stream
  1542. 98 CutStream completes the current primitive topology at the specified stream
  1543. 99 EmitThenCutStream equivalent to an EmitStream followed by a CutStream
  1544. 100 GSInstanceID GSInstanceID
  1545. 101 MakeDouble creates a double value
  1546. 102 SplitDouble splits a double into low and high parts
  1547. 103 LoadOutputControlPoint LoadOutputControlPoint
  1548. 104 LoadPatchConstant LoadPatchConstant
  1549. 105 DomainLocation DomainLocation
  1550. 106 StorePatchConstant StorePatchConstant
  1551. 107 OutputControlPointID OutputControlPointID
  1552. 108 PrimitiveID PrimitiveID
  1553. 109 CycleCounterLegacy CycleCounterLegacy
  1554. 110 WaveIsFirstLane returns 1 for the first lane in the wave
  1555. 111 WaveGetLaneIndex returns the index of the current lane in the wave
  1556. 112 WaveGetLaneCount returns the number of lanes in the wave
  1557. 113 WaveAnyTrue returns 1 if any of the lane evaluates the value to true
  1558. 114 WaveAllTrue returns 1 if all the lanes evaluate the value to true
  1559. 115 WaveActiveAllEqual returns 1 if all the lanes have the same value
  1560. 116 WaveActiveBallot returns a struct with a bit set for each lane where the condition is true
  1561. 117 WaveReadLaneAt returns the value from the specified lane
  1562. 118 WaveReadLaneFirst returns the value from the first lane
  1563. 119 WaveActiveOp returns the result the operation across waves
  1564. 120 WaveActiveBit returns the result of the operation across all lanes
  1565. 121 WavePrefixOp returns the result of the operation on prior lanes
  1566. 122 QuadReadLaneAt reads from a lane in the quad
  1567. 123 QuadOp returns the result of a quad-level operation
  1568. 124 BitcastI16toF16 bitcast between different sizes
  1569. 125 BitcastF16toI16 bitcast between different sizes
  1570. 126 BitcastI32toF32 bitcast between different sizes
  1571. 127 BitcastF32toI32 bitcast between different sizes
  1572. 128 BitcastI64toF64 bitcast between different sizes
  1573. 129 BitcastF64toI64 bitcast between different sizes
  1574. 130 LegacyF32ToF16 legacy fuction to convert float (f32) to half (f16) (this is not related to min-precision)
  1575. 131 LegacyF16ToF32 legacy fuction to convert half (f16) to float (f32) (this is not related to min-precision)
  1576. 132 LegacyDoubleToFloat legacy fuction to convert double to float
  1577. 133 LegacyDoubleToSInt32 legacy fuction to convert double to int32
  1578. 134 LegacyDoubleToUInt32 legacy fuction to convert double to uint32
  1579. 135 WaveAllBitCount returns the count of bits set to 1 across the wave
  1580. 136 WavePrefixBitCount returns the count of bits set to 1 on prior lanes
  1581. 137 AttributeAtVertex_ returns the values of the attributes at the vertex.
  1582. 138 ViewID returns the view index
  1583. === ============================= =================================================================================================================
  1584. Acos
  1585. ~~~~
  1586. The return value is within the range of -PI/2 to PI/2.
  1587. +----------+------+--------------+---------+------+------+---------+------+-----+
  1588. | src | -inf | [-1,1] | -denorm | -0 | +0 | +denorm | +inf | NaN |
  1589. +----------+------+--------------+---------+------+------+---------+------+-----+
  1590. | acos(src)| NaN | (-PI/2,+PI/2)| PI/2 | PI/2 | PI/2 | PI/2 | NaN | NaN |
  1591. +----------+------+--------------+---------+------+------+---------+------+-----+
  1592. Asin
  1593. ~~~~
  1594. The return value is within the range of -PI/2 to PI/2.
  1595. +----------+------+--------------+---------+------+------+---------+------+-----+
  1596. | src | -inf | [-1,1] | -denorm | -0 | +0 | +denorm | +inf | NaN |
  1597. +----------+------+--------------+---------+------+------+---------+------+-----+
  1598. | asin(src)| NaN | (-PI/2,+PI/2)| 0 | 0 | 0 | 0 | NaN | NaN |
  1599. +----------+------+--------------+---------+------+------+---------+------+-----+
  1600. Atan
  1601. ~~~~
  1602. +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+
  1603. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F |+inf | NaN |
  1604. +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+
  1605. | atan(src)| -PI/2| (-PI/2,+PI/2)| 0 | 0 | 0 | 0 | (-PI/2,+PI/2) |PI/2 | NaN |
  1606. +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+
  1607. Returns the arctangent of the specified value. The return value is within the range of -PI/2 to PI/2
  1608. AttributeAtVertex
  1609. ~~~~~~~~~~~~~~~~~
  1610. returns the values of the attributes at the vertex. VertexID ranges from 0 to 2.
  1611. Bfi
  1612. ~~~
  1613. Given a bit range from the LSB of a number, place that number of bits in another number at any offset.
  1614. dst = Bfi(src0, src1, src2, src3);
  1615. The LSB 5 bits of src0 provide the bitfield width (0-31) to take from src2.
  1616. The LSB 5 bits of src1 provide the bitfield offset (0-31) to start replacing bits in the number read from src3.
  1617. Given width, offset: bitmask = (((1 << width)-1) << offset) & 0xffffffff, dest = ((src2 << offset) & bitmask) | (src3 & ~bitmask)
  1618. Bfrev
  1619. ~~~~~
  1620. Reverses the order of the bits. For example given 0x12345678 the result would be 0x1e6a2c48.
  1621. Cos
  1622. ~~~
  1623. Theta values can be any IEEE 32-bit floating point values.
  1624. The maximum absolute error is 0.0008 in the interval from -100*Pi to +100*Pi.
  1625. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1626. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1627. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1628. | cos(src) | NaN | [-1 to +1] | +1 | +1 | +1 | +1 | [-1 to +1] | NaN | NaN |
  1629. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1630. Countbits
  1631. ~~~~~~~~~
  1632. Counts the number of bits in the input integer.
  1633. DerivCoarseX
  1634. ~~~~~~~~~~~~
  1635. dst = DerivCoarseX(src);
  1636. Computes the rate of change per stamp in x direction. Only a single x derivative pair is computed for each 2x2 stamp of pixels.
  1637. The data in the current Pixel Shader invocation may or may not participate in the calculation of the requested derivative, given the derivative will be calculated only once per 2x2 quad:
  1638. As an example, the x derivative could be a delta from the top row of pixels.
  1639. The exact calculation is up to the hardware vendor. There is also no specification dictating how the 2x2 quads will be aligned/tiled over a primitive.
  1640. DerivCoarseY
  1641. ~~~~~~~~~~~~
  1642. dst = DerivCoarseY(src);
  1643. Computes the rate of change per stamp in y direction. Only a single y derivative pair is computed for each 2x2 stamp of pixels.
  1644. The data in the current Pixel Shader invocation may or may not participate in the calculation of the requested derivative, given the derivative will be calculated only once per 2x2 quad:
  1645. As an example, the y derivative could be a delta from the left column of pixels.
  1646. The exact calculation is up to the hardware vendor. There is also no specification dictating how the 2x2 quads will be aligned/tiled over a primitive.
  1647. DerivFineX
  1648. ~~~~~~~~~~
  1649. dst = DerivFineX(src);
  1650. Computes the rate of change per pixel in x direction. Each pixel in the 2x2 stamp gets a unique pair of x derivative calculations
  1651. The data in the current Pixel Shader invocation always participates in the calculation of the requested derivative.
  1652. There is no specification dictating how the 2x2 quads will be aligned/tiled over a primitive.
  1653. DerivFineY
  1654. ~~~~~~~~~~
  1655. dst = DerivFineY(src);
  1656. Computes the rate of change per pixel in y direction. Each pixel in the 2x2 stamp gets a unique pair of y derivative calculations
  1657. The data in the current Pixel Shader invocation always participates in the calculation of the requested derivative.
  1658. There is no specification dictating how the 2x2 quads will be aligned/tiled over a primitive.
  1659. Dot2
  1660. ~~~~
  1661. Two-dimensional vector dot-product
  1662. Dot3
  1663. ~~~~
  1664. Three-dimensional vector dot-product
  1665. Dot4
  1666. ~~~~
  1667. Four-dimensional vector dot-product
  1668. Exp
  1669. ~~~
  1670. Returns 2^exponent. Note that hlsl log intrinsic returns the base-e exponent. Maximum relative error is e^-21.
  1671. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1672. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1673. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1674. | exp(src) | 0 | +F | 1 | 1 | 1 | 1 | +F | +inf | NaN |
  1675. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1676. FAbs
  1677. ~~~~
  1678. The FAbs instruction takes simply forces the sign of the number(s) on the source operand positive, including on INF and denorm values.
  1679. Applying FAbs on NaN preserves NaN, although the particular NaN bit pattern that results is not defined.
  1680. FMad
  1681. ~~~~
  1682. Floating point multiply & add. This operation is not fused for "precise" operations.
  1683. FMad(a,b,c) = a * b + c
  1684. FMax
  1685. ~~~~
  1686. >= is used instead of > so that if min(x,y) = x then max(x,y) = y.
  1687. NaN has special handling: If one source operand is NaN, then the other source operand is returned.
  1688. If both are NaN, any NaN representation is returned.
  1689. This conforms to new IEEE 754R rules.
  1690. Denorms are flushed (sign preserved) before comparison, however the result written to dest may or may not be denorm flushed.
  1691. +------+-----------------------------+
  1692. | a | b |
  1693. | +------+--------+------+------+
  1694. | | -inf | F | +inf | NaN |
  1695. +------+------+--------+------+------+
  1696. | -inf | -inf | b | +inf | -inf |
  1697. +------+------+--------+------+------+
  1698. | F | a | a or b | +inf | a |
  1699. +------+------+--------+------+------+
  1700. | +inf | +inf | +inf | +inf | +inf |
  1701. +------+------+--------+------+------+
  1702. | NaN | -inf | b | +inf | NaN |
  1703. +------+------+--------+------+------+
  1704. FMin
  1705. ~~~~
  1706. NaN has special handling: If one source operand is NaN, then the other source operand is returned.
  1707. If both are NaN, any NaN representation is returned.
  1708. This conforms to new IEEE 754R rules.
  1709. Denorms are flushed (sign preserved) before comparison, however the result written to dest may or may not be denorm flushed.
  1710. +------+-----------------------------+
  1711. | a | b |
  1712. | +------+--------+------+------+
  1713. | | -inf | F | +inf | NaN |
  1714. +------+------+--------+------+------+
  1715. | -inf | -inf | -inf | -inf | -inf |
  1716. +------+------+--------+------+------+
  1717. | F | -inf | a or b | a | a |
  1718. +------+------+--------+------+------+
  1719. | +inf | -inf | b | +inf | +inf |
  1720. +------+------+--------+------+------+
  1721. | NaN | -inf | b | +inf | NaN |
  1722. +------+------+--------+------+------+
  1723. FirstbitHi
  1724. ~~~~~~~~~~
  1725. Returns the integer position of the first bit set in the 32-bit input starting from the MSB. For example, 0x10000000 would return 3. Returns 0xffffffff if no match was found.
  1726. FirstbitLo
  1727. ~~~~~~~~~~
  1728. Returns the integer position of the first bit set in the 32-bit input starting from the LSB. For example, 0x00000000 would return 1. Returns 0xffffffff if no match was found.
  1729. FirstbitSHi
  1730. ~~~~~~~~~~~
  1731. Returns the first 0 from the MSB if the number is negative, else the first 1 from the MSB. Returns 0xffffffff if no match was found.
  1732. Fma
  1733. ~~~
  1734. Fused multiply-add. This operation is only defined in double precision.
  1735. Fma(a,b,c) = a * b + c
  1736. Frc
  1737. ~~~
  1738. +--------------+------+------+---------+----+----+---------+--------+------+-----+
  1739. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1740. +--------------+------+------+---------+----+----+---------+--------+------+-----+
  1741. | log(src) | NaN |[+0,1)| +0 | +0 | +0 | +0 | [+0,1) | NaN | NaN |
  1742. +--------------+------+------+---------+----+----+---------+--------+------+-----+
  1743. Hcos
  1744. ~~~~
  1745. Returns the hyperbolic cosine of the specified value.
  1746. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1747. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1748. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1749. | hcos(src)| +inf | (1, +inf) | +1 | +1 | +1 | +1 | (1, +inf) | +inf | NaN |
  1750. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1751. Hsin
  1752. ~~~~
  1753. Returns the hyperbolic sine of the specified value.
  1754. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1755. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1756. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1757. | hsin(src)| -inf | -F | 0 | 0 | 0 | 0 | +F | +inf | NaN |
  1758. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1759. Htan
  1760. ~~~~
  1761. Returns the hyperbolic tangent of the specified value.
  1762. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1763. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1764. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1765. | htan(src)| -1 | -F | 0 | 0 | 0 | 0 | +F | +1 | NaN |
  1766. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1767. IMad
  1768. ~~~~
  1769. Signed integer multiply & add
  1770. IMad(a,b,c) = a * b + c
  1771. IMax
  1772. ~~~~
  1773. IMax(a,b) returns a if a > b, else b. Optional negate modifier on source operands takes 2's complement before performing operation.
  1774. IMin
  1775. ~~~~
  1776. IMin(a,b) returns a if a < b, else b. Optional negate modifier on source operands takes 2's complement before performing operation.
  1777. IMul
  1778. ~~~~
  1779. IMul(src0, src1) = destHi, destLo
  1780. multiply of 32-bit operands src0 and src1 (note they are signed), producing the correct full 64-bit result.
  1781. The low 32 bits are placed in destLO. The high 32 bits are placed in destHI.
  1782. Either of destHI or destLO may be specified as NULL instead of specifying a register, in the case high or low 32 bits of the 64-bit result are not needed.
  1783. Optional negate modifier on source operands takes 2's complement before performing arithmetic operation.
  1784. Ibfe
  1785. ~~~~
  1786. dest = Ibfe(src0, src1, src2)
  1787. Given a range of bits in a number, shift those bits to the LSB and sign extend the MSB of the range.
  1788. width : The LSB 5 bits of src0 (0-31).
  1789. offset: The LSB 5 bits of src1 (0-31)
  1790. .. code:: c
  1791. if( width == 0 )
  1792. {
  1793. dest = 0
  1794. }
  1795. else if( width + offset < 32 )
  1796. {
  1797. shl dest, src2, 32-(width+offset)
  1798. ishr dest, dest, 32-width
  1799. }
  1800. else
  1801. {
  1802. ishr dest, src2, offset
  1803. }
  1804. IsFinite
  1805. ~~~~~~~~
  1806. Returns true if x is finite, false otherwise.
  1807. IsInf
  1808. ~~~~~
  1809. Returns true if x is +INF or -INF, false otherwise.
  1810. IsNaN
  1811. ~~~~~
  1812. Returns true if x is NAN or QNAN, false otherwise.
  1813. IsNormal
  1814. ~~~~~~~~
  1815. Returns IsNormal.
  1816. LoadInput
  1817. ~~~~~~~~~
  1818. Loads the value from shader input
  1819. Log
  1820. ~~~
  1821. Returns log base 2. Note that hlsl log intrinsic returns natural log.
  1822. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1823. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1824. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1825. | log(src) | NaN | NaN | -inf |-inf|-inf| -inf | F | +inf | NaN |
  1826. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1827. MinPrecXRegLoad
  1828. ~~~~~~~~~~~~~~~
  1829. Helper load operation for minprecision
  1830. MinPrecXRegStore
  1831. ~~~~~~~~~~~~~~~~
  1832. Helper store operation for minprecision
  1833. Msad
  1834. ~~~~
  1835. Returns the masked Sum of Absolute Differences.
  1836. dest = msad(ref, src, accum)
  1837. ref: contains 4 packed 8-bit unsigned integers in 32 bits.
  1838. src: contains 4 packed 8-bit unsigned integers in 32 bits.
  1839. accum: a 32-bit unsigned integer, providing an existing accumulation.
  1840. dest receives the result of the masked SAD operation added to the accumulation value.
  1841. .. code:: c
  1842. UINT msad( UINT ref, UINT src, UINT accum )
  1843. {
  1844. for (UINT i = 0; i < 4; i++)
  1845. {
  1846. BYTE refByte, srcByte, absDiff;
  1847. refByte = (BYTE)(ref >> (i * 8));
  1848. if (!refByte)
  1849. {
  1850. continue;
  1851. }
  1852. srcByte = (BYTE)(src >> (i * 8));
  1853. if (refByte >= srcByte)
  1854. {
  1855. absDiff = refByte - srcByte;
  1856. }
  1857. else
  1858. {
  1859. absDiff = srcByte - refByte;
  1860. }
  1861. // The recommended overflow behavior for MSAD is
  1862. // to do a 32-bit saturate. This is not
  1863. // required, however, and wrapping is allowed.
  1864. // So from an application point of view,
  1865. // overflow behavior is undefined.
  1866. if (UINT_MAX - accum < absDiff)
  1867. {
  1868. accum = UINT_MAX;
  1869. break;
  1870. }
  1871. accum += absDiff;
  1872. }
  1873. return accum;
  1874. }
  1875. Round_ne
  1876. ~~~~~~~~
  1877. Floating-point round of the values in src,
  1878. writing integral floating-point values to dest.
  1879. round_ne rounds towards nearest even. For halfway, it rounds away from zero.
  1880. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1881. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1882. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1883. | round_ne(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1884. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1885. Round_ni
  1886. ~~~~~~~~
  1887. Floating-point round of the values in src,
  1888. writing integral floating-point values to dest.
  1889. round_ni rounds towards -INF, commonly known as floor().
  1890. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1891. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1892. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1893. | round_ni(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1894. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1895. Round_pi
  1896. ~~~~~~~~
  1897. Floating-point round of the values in src,
  1898. writing integral floating-point values to dest.
  1899. round_pi rounds towards +INF, commonly known as ceil().
  1900. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1901. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1902. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1903. | round_pi(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1904. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1905. Round_z
  1906. ~~~~~~~
  1907. Floating-point round of the values in src,
  1908. writing integral floating-point values to dest.
  1909. round_z rounds towards zero.
  1910. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1911. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1912. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1913. | round_z(src) | -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1914. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1915. Rsqrt
  1916. ~~~~~
  1917. Maximum relative error is 2^21.
  1918. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1919. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1920. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1921. | rsqrt(src) | -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1922. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1923. Saturate
  1924. ~~~~~~~~
  1925. The Saturate instruction performs the following operation on its input value:
  1926. min(1.0f, max(0.0f, value))
  1927. where min() and max() in the above expression behave in the way Min and Max behave.
  1928. Saturate(NaN) returns 0, by the rules for min and max.
  1929. Sin
  1930. ~~~
  1931. Theta values can be any IEEE 32-bit floating point values.
  1932. The maximum absolute error is 0.0008 in the interval from -100*Pi to +100*Pi.
  1933. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1934. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1935. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1936. | sin(src) | NaN | [-1 to +1] | -0 | -0 | +0 | +0 | [-1 to +1] | NaN | NaN |
  1937. +----------+------+------------+---------+----+----+---------+------------+------+-----+
  1938. Sqrt
  1939. ~~~~
  1940. Precision is 1 ulp.
  1941. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1942. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1943. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1944. | sqrt(src) | NaN | NaN| -0 | -0 | +0 | +0 | +F | +inf | NaN |
  1945. +--------------+------+----+---------+----+----+---------+----+------+-----+
  1946. StoreOutput
  1947. ~~~~~~~~~~~
  1948. Stores the value to shader output
  1949. Tan
  1950. ~~~
  1951. Theta values can be any IEEE 32-bit floating point values.
  1952. +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+
  1953. | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN |
  1954. +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+
  1955. | tan(src) | NaN | [-inf to +inf] | -0 | -0 | +0 | +0 | [-inf to +inf] | NaN | NaN |
  1956. +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+
  1957. TempRegLoad
  1958. ~~~~~~~~~~~
  1959. Helper load operation
  1960. TempRegStore
  1961. ~~~~~~~~~~~~
  1962. Helper store operation
  1963. UAddc
  1964. ~~~~~
  1965. dest0, dest1 = UAddc(src0, src1)
  1966. unsigned add of 32-bit operands src0 and src1, placing the LSB part of the 32-bit result in dest0.
  1967. dest1 is written with: 1 if a carry is produced, 0 otherwise. Dest1 can be NULL if the carry is not needed
  1968. UDiv
  1969. ~~~~
  1970. destQUOT, destREM = UDiv(src0, src1);
  1971. unsigned divide of the 32-bit operand src0 by the 32-bit operand src1.
  1972. The results of the divides are the 32-bit quotients (placed in destQUOT) and 32-bit remainders (placed in destREM).
  1973. Divide by zero returns 0xffffffff for both quotient and remainder.
  1974. Either destQUOT or destREM may be specified as NULL instead of specifying a register, in the case the quotient or remainder are not needed.
  1975. Unsigned subtract of 32-bit operands src1 from src0, placing the LSB part of the 32-bit result in dest0.
  1976. dest1 is written with: 1 if a borrow is produced, 0 otherwise. Dest1 can be NULL if the borrow is not needed
  1977. UMad
  1978. ~~~~
  1979. Unsigned integer multiply & add.
  1980. Umad(a,b,c) = a * b + c
  1981. UMax
  1982. ~~~~
  1983. unsigned integer maximum. UMax(a,b) = a > b ? a : b
  1984. UMin
  1985. ~~~~
  1986. unsigned integer minimum. UMin(a,b) = a < b ? a : b
  1987. UMul
  1988. ~~~~
  1989. multiply of 32-bit operands src0 and src1 (note they are unsigned), producing the correct full 64-bit result.
  1990. The low 32 bits are placed in destLO. The high 32 bits are placed in destHI.
  1991. Either of destHI or destLO may be specified as NULL instead of specifying a register, in the case high or low 32 bits of the 64-bit result are not needed
  1992. USubb
  1993. ~~~~~
  1994. dest0, dest1 = USubb(src0, src1)
  1995. Ubfe
  1996. ~~~~
  1997. dest = ubfe(src0, src1, src2)
  1998. Given a range of bits in a number, shift those bits to the LSB and set remaining bits to 0.
  1999. width : The LSB 5 bits of src0 (0-31).
  2000. offset: The LSB 5 bits of src1 (0-31).
  2001. Given width, offset:
  2002. .. code:: c
  2003. if( width == 0 )
  2004. {
  2005. dest = 0
  2006. }
  2007. else if( width + offset < 32 )
  2008. {
  2009. shl dest, src2, 32-(width+offset)
  2010. ushr dest, dest, 32-width
  2011. }
  2012. else
  2013. {
  2014. ushr dest, src2, offset
  2015. }
  2016. .. OPCODES-RST:END
  2017. Custom instructions
  2018. -------------------
  2019. Instructions for third-party extensions will be specially-prefixed external function calls, identified by a declared extension-set-prefix. Additional metadata will be included to provide hints about uniformity, pure or const guarantees, alignment, etc.
  2020. Validation Rules
  2021. ================
  2022. The following rules are verified by the *Validator* component and thus can be relied upon by downstream consumers.
  2023. The set of validation rules that are known to hold for a DXIL program is identifier by the 'dx.valver' named metadata node, which consists of a two-element tuple of constant int values, a major and minor version. Minor version numbers are increments as rules are added to a prior table or as the implementation fixes issues.
  2024. .. <py::lines('VALRULES-RST')>hctdb_instrhelp.get_valrules_rst()</py>
  2025. .. VALRULES-RST:BEGIN
  2026. ====================================== =======================================================================================================================================================================================================================================================================================================
  2027. Rule Code Description
  2028. ====================================== =======================================================================================================================================================================================================================================================================================================
  2029. BITCODE.VALID TODO - Module must be bitcode-valid
  2030. CONTAINER.PARTINVALID DXIL Container must not contain unknown parts
  2031. CONTAINER.PARTMATCHES DXIL Container Parts must match Module
  2032. CONTAINER.PARTMISSING DXIL Container requires certain parts, corresponding to module
  2033. CONTAINER.PARTREPEATED DXIL Container must have only one of each part type
  2034. CONTAINER.ROOTSIGNATUREINCOMPATIBLE Root Signature in DXIL Container must be compatible with shader
  2035. DECL.DXILFNEXTERN External function must be a DXIL function
  2036. DECL.DXILNSRESERVED The DXIL reserved prefixes must only be used by built-in functions and types
  2037. DECL.FNFLATTENPARAM Function parameters must not use struct types
  2038. DECL.FNISCALLED Functions can only be used by call instructions
  2039. DECL.NOTUSEDEXTERNAL External declaration should not be used
  2040. DECL.USEDEXTERNALFUNCTION External function must be used
  2041. DECL.USEDINTERNAL Internal declaration must be used
  2042. FLOW.DEADLOOP Loop must have break
  2043. FLOW.FUNCTIONCALL Function with parameter is not permitted
  2044. FLOW.NORECUSION Recursion is not permitted
  2045. FLOW.REDUCIBLE Execution flow must be reducible
  2046. INSTR.ALLOWED Instructions must be of an allowed type
  2047. INSTR.ATTRIBUTEATVERTEXNOINTERPOLATION Attribute %0 must have nointerpolation mode in order to use GetAttributeAtVertex function.
  2048. INSTR.BARRIERMODEFORNONCS sync in a non-Compute Shader must only sync UAV (sync_uglobal)
  2049. INSTR.BARRIERMODENOMEMORY sync must include some form of memory barrier - _u (UAV) and/or _g (Thread Group Shared Memory). Only _t (thread group sync) is optional.
  2050. INSTR.BARRIERMODEUSELESSUGROUP sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.
  2051. INSTR.BUFFERUPDATECOUNTERONUAV BufferUpdateCounter valid only on UAV
  2052. INSTR.CALLOLOAD Call to DXIL intrinsic must match overload signature
  2053. INSTR.CANNOTPULLPOSITION pull-model evaluation of position disallowed
  2054. INSTR.CBUFFERCLASSFORCBUFFERHANDLE Expect Cbuffer for CBufferLoad handle
  2055. INSTR.CBUFFEROUTOFBOUND Cbuffer access out of bound
  2056. INSTR.COORDINATECOUNTFORRAWTYPEDBUF raw/typed buffer don't need 2 coordinates
  2057. INSTR.COORDINATECOUNTFORSTRUCTBUF structured buffer require 2 coordinates
  2058. INSTR.DXILSTRUCTUSER Dxil struct types should only used by ExtractValue
  2059. INSTR.DXILSTRUCTUSEROUTOFBOUND Index out of bound when extract value from dxil struct types
  2060. INSTR.EVALINTERPOLATIONMODE Interpolation mode on %0 used with eval_* instruction must be linear, linear_centroid, linear_noperspective, linear_noperspective_centroid, linear_sample or linear_noperspective_sample
  2061. INSTR.EXTRACTVALUE ExtractValue should only be used on dxil struct types and cmpxchg
  2062. INSTR.FAILTORESLOVETGSMPOINTER TGSM pointers must originate from an unambiguous TGSM global variable.
  2063. INSTR.HANDLENOTFROMCREATEHANDLE Resource handle should returned by createHandle
  2064. INSTR.IMMBIASFORSAMPLEB bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate
  2065. INSTR.INBOUNDSACCESS Access to out-of-bounds memory is disallowed
  2066. INSTR.MINPRECISIONNOTPRECISE Instructions marked precise may not refer to minprecision values
  2067. INSTR.MINPRECISONBITCAST Bitcast on minprecison types is not allowed
  2068. INSTR.MIPLEVELFORGETDIMENSION Use mip level on buffer when GetDimensions
  2069. INSTR.MIPONUAVLOAD uav load don't support mipLevel/sampleIndex
  2070. INSTR.NOGENERICPTRADDRSPACECAST Address space cast between pointer types must have one part to be generic address space
  2071. INSTR.NOIDIVBYZERO No signed integer division by zero
  2072. INSTR.NOINDEFINITEACOS No indefinite arccosine
  2073. INSTR.NOINDEFINITEASIN No indefinite arcsine
  2074. INSTR.NOINDEFINITEDSXY No indefinite derivative calculation
  2075. INSTR.NOINDEFINITELOG No indefinite logarithm
  2076. INSTR.NOREADINGUNINITIALIZED Instructions should not read uninitialized value
  2077. INSTR.NOUDIVBYZERO No unsigned integer division by zero
  2078. INSTR.OFFSETONUAVLOAD uav load don't support offset
  2079. INSTR.OLOAD DXIL intrinsic overload must be valid
  2080. INSTR.ONLYONEALLOCCONSUME RWStructuredBuffers may increment or decrement their counters, but not both.
  2081. INSTR.OPCODERESERVED Instructions must not reference reserved opcodes
  2082. INSTR.OPCONST DXIL intrinsic requires an immediate constant operand
  2083. INSTR.OPCONSTRANGE Constant values must be in-range for operation
  2084. INSTR.OPERANDRANGE DXIL intrinsic operand must be within defined range
  2085. INSTR.PTRBITCAST Pointer type bitcast must be have same size
  2086. INSTR.RESOURCECLASSFORLOAD load can only run on UAV/SRV resource
  2087. INSTR.RESOURCECLASSFORSAMPLERGATHER sample, lod and gather should on srv resource.
  2088. INSTR.RESOURCECLASSFORUAVSTORE store should on uav resource.
  2089. INSTR.RESOURCECOORDINATEMISS coord uninitialized
  2090. INSTR.RESOURCECOORDINATETOOMANY out of bound coord must be undef
  2091. INSTR.RESOURCEKINDFORBUFFERLOADSTORE buffer load/store only works on Raw/Typed/StructuredBuffer
  2092. INSTR.RESOURCEKINDFORCALCLOD lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray
  2093. INSTR.RESOURCEKINDFORGATHER gather requires resource declared as texture/2D/Cube/2DArray/CubeArray
  2094. INSTR.RESOURCEKINDFORGETDIM Invalid resource kind on GetDimensions
  2095. INSTR.RESOURCEKINDFORSAMPLE sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray
  2096. INSTR.RESOURCEKINDFORSAMPLEC samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray
  2097. INSTR.RESOURCEKINDFORTEXTURELOAD texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray
  2098. INSTR.RESOURCEKINDFORTEXTURESTORE texture store only works on Texture1D/1DArray/2D/2DArray/3D
  2099. INSTR.RESOURCEOFFSETMISS offset uninitialized
  2100. INSTR.RESOURCEOFFSETTOOMANY out of bound offset must be undef
  2101. INSTR.SAMPLECOMPTYPE sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.
  2102. INSTR.SAMPLEINDEXFORLOAD2DMS load on Texture2DMS/2DMSArray require sampleIndex
  2103. INSTR.SAMPLERMODEFORLOD lod instruction requires sampler declared in default mode
  2104. INSTR.SAMPLERMODEFORSAMPLE sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode
  2105. INSTR.SAMPLERMODEFORSAMPLEC sample_c_*/gather_c instructions require sampler declared in comparison mode
  2106. INSTR.STRUCTBITCAST Bitcast on struct types is not allowed
  2107. INSTR.TEXTUREOFFSET offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7
  2108. INSTR.TGSMRACECOND Race condition writing to shared memory detected, consider making this write conditional
  2109. INSTR.UNDEFRESULTFORGETDIMENSION GetDimensions used undef dimension %0 on %1
  2110. INSTR.WRITEMASKFORTYPEDUAVSTORE store on typed uav must write to all four components of the UAV
  2111. INSTR.WRITEMASKMATCHVALUEFORUAVSTORE uav store write mask must match store value mask, write mask is %0 and store value mask is %1
  2112. META.BARYCENTRICSFLOAT3 only 'float3' type is allowed for SV_Barycentrics.
  2113. META.BARYCENTRICSINTERPOLATION SV_Barycentrics cannot be used with 'nointerpolation' type
  2114. META.BARYCENTRICSTWOPERSPECTIVES There can only be up to two input attributes of SV_Barycentrics with different perspective interpolation mode.
  2115. META.BRANCHFLATTEN Can't use branch and flatten attributes together
  2116. META.CLIPCULLMAXCOMPONENTS Combined elements of SV_ClipDistance and SV_CullDistance must fit in 8 components
  2117. META.CLIPCULLMAXROWS Combined elements of SV_ClipDistance and SV_CullDistance must fit in two rows.
  2118. META.CONTROLFLOWHINTNOTONCONTROLFLOW Control flow hint only works on control flow inst
  2119. META.DENSERESIDS Resource identifiers must be zero-based and dense
  2120. META.DUPLICATESYSVALUE System value may only appear once in signature
  2121. META.ENTRYFUNCTION entrypoint not found
  2122. META.FLAGSUSAGE Flags must match usage
  2123. META.FORCECASEONSWITCH Attribute forcecase only works for switch
  2124. META.FUNCTIONANNOTATION Cannot find function annotation for %0
  2125. META.GLCNOTONAPPENDCONSUME globallycoherent cannot be used with append/consume buffers
  2126. META.INTEGERINTERPMODE Interpolation mode on integer must be Constant
  2127. META.INTERPMODEINONEROW Interpolation mode must be identical for all elements packed into the same row.
  2128. META.INTERPMODEVALID Interpolation mode must be valid
  2129. META.INVALIDCONTROLFLOWHINT Invalid control flow hint
  2130. META.KNOWN Named metadata should be known
  2131. META.MAXTESSFACTOR Hull Shader MaxTessFactor must be [%0..%1]. %2 specified
  2132. META.NOSEMANTICOVERLAP Semantics must not overlap
  2133. META.REQUIRED TODO - Required metadata missing
  2134. META.SEMAKINDMATCHESNAME Semantic name must match system value, when defined.
  2135. META.SEMAKINDVALID Semantic kind must be valid
  2136. META.SEMANTICCOMPTYPE %0 must be %1
  2137. META.SEMANTICINDEXMAX System value semantics have a maximum valid semantic index
  2138. META.SEMANTICLEN Semantic length must be at least 1 and at most 64
  2139. META.SEMANTICSHOULDBEALLOCATED Semantic should have a valid packing location
  2140. META.SEMANTICSHOULDNOTBEALLOCATED Semantic should have a packing location of -1
  2141. META.SIGNATURECOMPTYPE signature %0 specifies unrecognized or invalid component type
  2142. META.SIGNATUREILLEGALCOMPONENTORDER Component ordering for packed elements must be: arbitrary < system value < system generated value
  2143. META.SIGNATUREINDEXCONFLICT Only elements with compatible indexing rules may be packed together
  2144. META.SIGNATUREOUTOFRANGE Signature elements must fit within maximum signature size
  2145. META.SIGNATUREOVERLAP Signature elements may not overlap in packing location.
  2146. META.STRUCTBUFALIGNMENT StructuredBuffer stride not aligned
  2147. META.STRUCTBUFALIGNMENTOUTOFBOUND StructuredBuffer stride out of bounds
  2148. META.SYSTEMVALUEROWS System value may only have 1 row
  2149. META.TARGET Target triple must be 'dxil-ms-dx'
  2150. META.TESSELLATOROUTPUTPRIMITIVE Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.
  2151. META.TESSELLATORPARTITION Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.
  2152. META.TEXTURETYPE elements of typed buffers and textures must fit in four 32-bit quantities
  2153. META.USED All metadata must be used by dxil
  2154. META.VALIDSAMPLERMODE Invalid sampler mode on sampler
  2155. META.VALUERANGE Metadata value must be within range
  2156. META.WELLFORMED TODO - Metadata must be well-formed in operand count and types
  2157. SM.APPENDANDCONSUMEONSAMEUAV BufferUpdateCounter inc and dec on a given UAV (%d) cannot both be in the same shader for shader model less than 5.1.
  2158. SM.CBUFFERELEMENTOVERFLOW CBuffer elements must not overflow
  2159. SM.CBUFFEROFFSETOVERLAP CBuffer offsets must not overlap
  2160. SM.CBUFFERTEMPLATETYPEMUSTBESTRUCT D3D12 constant/texture buffer template element can only be a struct
  2161. SM.COMPLETEPOSITION Not all elements of SV_Position were written
  2162. SM.COUNTERONLYONSTRUCTBUF BufferUpdateCounter valid only on structured buffers
  2163. SM.CSNORETURN Compute shaders can't return values, outputs must be written in writable resources (UAVs).
  2164. SM.DOMAINLOCATIONIDXOOB DomainLocation component index out of bounds for the domain.
  2165. SM.DSINPUTCONTROLPOINTCOUNTRANGE DS input control point count must be [0..%0]. %1 specified
  2166. SM.DXILVERSION Target shader model requires specific Dxil Version
  2167. SM.GSINSTANCECOUNTRANGE GS instance count must be [1..%0]. %1 specified
  2168. SM.GSOUTPUTVERTEXCOUNTRANGE GS output vertex count must be [0..%0]. %1 specified
  2169. SM.GSTOTALOUTPUTVERTEXDATARANGE Declared output vertex count (%0) multiplied by the total number of declared scalar components of output data (%1) equals %2. This value cannot be greater than %3
  2170. SM.GSVALIDINPUTPRIMITIVE GS input primitive unrecognized
  2171. SM.GSVALIDOUTPUTPRIMITIVETOPOLOGY GS output primitive topology unrecognized
  2172. SM.HSINPUTCONTROLPOINTCOUNTRANGE HS input control point count must be [0..%0]. %1 specified
  2173. SM.HULLPASSTHRUCONTROLPOINTCOUNTMATCH For pass thru hull shader, input control point count must match output control point count
  2174. SM.INSIDETESSFACTORSIZEMATCHDOMAIN InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.
  2175. SM.INVALIDRESOURCECOMPTYPE Invalid resource return type
  2176. SM.INVALIDRESOURCEKIND Invalid resources kind
  2177. SM.INVALIDTEXTUREKINDONUAV Texture2DMS[Array] or TextureCube[Array] resources are not supported with UAVs
  2178. SM.ISOLINEOUTPUTPRIMITIVEMISMATCH Hull Shader declared with IsoLine Domain must specify output primitive point or line. Triangle_cw or triangle_ccw output are not compatible with the IsoLine Domain.
  2179. SM.MAXTGSMSIZE Total Thread Group Shared Memory storage is %0, exceeded %1
  2180. SM.MAXTHEADGROUP Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1
  2181. SM.MULTISTREAMMUSTBEPOINT When multiple GS output streams are used they must be pointlists
  2182. SM.NAME Target shader model name must be known
  2183. SM.NOINTERPMODE Interpolation mode must be undefined for VS input/PS output/patch constant.
  2184. SM.NOPSOUTPUTIDX Pixel shader output registers are not indexable.
  2185. SM.OPCODE Opcode must be defined in target shader model
  2186. SM.OPCODEININVALIDFUNCTION Invalid DXIL opcode usage like StorePatchConstant in patch constant function
  2187. SM.OPERAND Operand must be defined in target shader model
  2188. SM.OUTPUTCONTROLPOINTCOUNTRANGE output control point count must be [0..%0]. %1 specified
  2189. SM.OUTPUTCONTROLPOINTSTOTALSCALARS Total number of scalars across all HS output control points must not exceed
  2190. SM.PATCHCONSTANTONLYFORHSDS patch constant signature only valid in HS and DS
  2191. SM.PSCONSISTENTINTERP Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE and not running at sample frequency (which is forced by inputting SV_SampleIndex or declaring an input linear_sample or linear_noperspective_sample)
  2192. SM.PSCOVERAGEANDINNERCOVERAGE InnerCoverage and Coverage are mutually exclusive.
  2193. SM.PSMULTIPLEDEPTHSEMANTIC Pixel Shader only allows one type of depth semantic to be declared
  2194. SM.PSOUTPUTSEMANTIC Pixel Shader allows output semantics to be SV_Target, SV_Depth, SV_DepthGreaterEqual, SV_DepthLessEqual, SV_Coverage or SV_StencilRef, %0 found
  2195. SM.PSTARGETCOL0 SV_Target packed location must start at column 0
  2196. SM.PSTARGETINDEXMATCHESROW SV_Target semantic index must match packed row location
  2197. SM.RESOURCERANGEOVERLAP Resource ranges must not overlap
  2198. SM.ROVONLYINPS RasterizerOrdered objects are only allowed in 5.0+ pixel shaders
  2199. SM.SAMPLECOUNTONLYON2DMS Only Texture2DMS/2DMSArray could has sample count
  2200. SM.SEMANTIC Semantic must be defined in target shader model
  2201. SM.STREAMINDEXRANGE Stream index (%0) must between 0 and %1
  2202. SM.TESSFACTORFORDOMAIN Required TessFactor for domain not found declared anywhere in Patch Constant data
  2203. SM.TESSFACTORSIZEMATCHDOMAIN TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.
  2204. SM.THREADGROUPCHANNELRANGE Declared Thread Group %0 size %1 outside valid range [%2..%3]
  2205. SM.TRIOUTPUTPRIMITIVEMISMATCH Hull Shader declared with Tri Domain must specify output primitive point, triangle_cw or triangle_ccw. Line output is not compatible with the Tri domain
  2206. SM.UNDEFINEDOUTPUT Not all elements of output %0 were written
  2207. SM.VALIDDOMAIN Invalid Tessellator Domain specified. Must be isoline, tri or quad
  2208. SM.VIEWIDNEEDSSLOT ViewID requires compatible space in pixel shader input signature
  2209. SM.ZEROHSINPUTCONTROLPOINTWITHINPUT When HS input control point count is 0, no input signature should exist
  2210. TYPES.DEFINED Type must be defined based on DXIL primitives
  2211. TYPES.I8 I8 can only used as immediate value for intrinsic
  2212. TYPES.INTWIDTH Int type must be of valid width
  2213. TYPES.NOMULTIDIM Only one dimension allowed for array type
  2214. TYPES.NOVECTOR Vector types must not be present
  2215. UNI.NOWAVESENSITIVEGRADIENT Gradient operations are not affected by wave-sensitive data or control flow.
  2216. ====================================== =======================================================================================================================================================================================================================================================================================================
  2217. .. VALRULES-RST:END
  2218. Modules and Linking
  2219. ===================
  2220. HLSL has linking capabilities to enable third-party libraries. The linking step happens before shader DXIL is given to the driver compilers.
  2221. Additional Notes
  2222. ================
  2223. These additional notes are not normative for DXIL, and are included for the convenience of implementers.
  2224. Other Versioned Components
  2225. --------------------------
  2226. In addition to shader model, DXIL and bitcode representation versions, two other interesting versioned components are discussed: the supporting operating system and runtime, and the HLSL language.
  2227. Support is provided in the Microsoft Windows family of operating systems, when running on the D3D12 runtime.
  2228. The HLSL language is versioned independently of DXIL, and currently follows an 'HLSL <year>' naming scheme. HLSL 2015 is the dialect supported by the d3dcompiler_47 library; a limited form of support is provided in the open source HLSL on LLVM project. HLSL 2016 is the version supported by the current HLSL on LLVM project, which removes some features (primarily effect framework syntax, backquote operator) and adds new ones (wave intrinsics and basic i64 support).
  2229. .. _dxil_container_format:
  2230. DXIL Container Format
  2231. ---------------------
  2232. DXIL is typically encapsulated in a DXIL container. A DXIL container is composed of a header, a sequence of part lengths, and a sequence of parts.
  2233. The following C declaration describes this structure::
  2234. struct DxilContainerHeader {
  2235. uint32_t HeaderFourCC;
  2236. uint8_t Digest[DxilContainerHashSize];
  2237. uint16_t MajorVersion;
  2238. uint16_t MinorVersion;
  2239. uint32_t ContainerSizeInBytes; // From start of this header
  2240. uint32_t PartCount;
  2241. // Structure is followed by uint32_t PartOffset[PartCount];
  2242. // The offset is to a DxilPartHeader.
  2243. };
  2244. Each part has a standard header, followed by a part-specify body::
  2245. struct DxilPartHeader {
  2246. uint32_t PartFourCC; // Four char code for part type.
  2247. uint32_t PartSize; // Byte count for PartData.
  2248. // Structure is followed by uint8_t PartData[PartSize].
  2249. };
  2250. The DXIL program is found in a part with the following body::
  2251. struct DxilProgramHeader {
  2252. uint32_t ProgramVersion; /// Major and minor version of shader, including type.
  2253. uint32_t SizeInUint32; /// Size in uint32_t units including this header.
  2254. uint32_t DxilMagic; // 0x4C495844, ASCII "DXIL".
  2255. uint32_t DxilVersion; // DXIL version.
  2256. uint32_t BitcodeOffset; // Offset to LLVM bitcode (from DxilMagic).
  2257. uint32_t BitcodeSize; // Size of LLVM bitcode.
  2258. // Followed by uint8_t[BitcodeHeader.BitcodeSize] after possible gap from BitcodeOffset
  2259. };
  2260. The bitcode payload is defined as per bitcode encoding.
  2261. Future Directions
  2262. -----------------
  2263. This section provides background on future directions for DXIL that may or may not materialize. They imply a new version of DXIL.
  2264. It's desirable to support generic pointers, pointing to one of other kinds of pointers. If the compiler fails to disambiguate, memory access is done via a generic pointer; the HLSL compiler will warn the user about each access that it cannot disambiguate. Not supported for SM6.
  2265. HLSL will eventually support more primitive types such as i8, i16, i32, i64, half, float, double, as well as declspec(align(n)) and #pragma pack(n) directives. SM6.0 will eventually require byte-granularity access support in hardware, especially writes. Not supported for SM6.
  2266. There will be a Requires32BitAlignedAccesses CAP flag. If absent, this would indicate that the shader requires writes that (1) do not write full four bytes, or (2) are not aligned on four-byte boundary. If hardware does not natively support these, the shader is rejected. Programmers can work around this hardware limitation by manually aligning smaller data on four-byte boundary in HLSL.
  2267. When libraries are supported as first-class DXIL constructs, "lib_*" shader models can specify more than one entry point per module; the other shader models must specify exactly one entry point.
  2268. The target machine specification for HLSL might specify a 64-bit pointer side with 64-bit offsets.
  2269. Hardware support for generic pointer is essential for HLSL next as a fallback mechanism for cases when compiler cannot disambiguate pointer's address space.
  2270. Future DXIL will change how half and i16 are treated:
  2271. * i16 will have to be supported natively either in hardware or via emulation,
  2272. * half's behavior will depend on the value of RequiresHardwareHalf CAP; if it's not set, half can be treated as min-precision type (min16float); i.e., computation may be done with values implicitly promoted to floats; if it's set and hardware does not support half type natively, the driver compiler can either emulate exact IEEE half behavior or fail shader creation.
  2273. Pending Specification Work
  2274. ==========================
  2275. The following work on this specification is still pending:
  2276. * Consider moving some additional tables and lists into hctdb and cross-reference.
  2277. * Complete the extended documentation for instructions.