DxilAddPixelHitInstrumentation.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilAddPixelHitInstrumentation.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // Provides a pass to add instrumentation to determine pixel hit count and //
  9. // cost. Used by PIX. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "dxc/DXIL/DxilOperations.h"
  13. #include "dxc/DXIL/DxilInstructions.h"
  14. #include "dxc/DXIL/DxilModule.h"
  15. #include "dxc/DXIL/DxilUtil.h"
  16. #include "dxc/DxilPIXPasses/DxilPIXPasses.h"
  17. #include "dxc/HLSL/DxilGenerationPass.h"
  18. #include "llvm/IR/PassManager.h"
  19. #include "llvm/Transforms/Utils/Local.h"
  20. using namespace llvm;
  21. using namespace hlsl;
  22. class DxilAddPixelHitInstrumentation : public ModulePass {
  23. bool ForceEarlyZ = false;
  24. bool AddPixelCost = false;
  25. int RTWidth = 1024;
  26. int NumPixels = 128;
  27. int SVPositionIndex = -1;
  28. public:
  29. static char ID; // Pass identification, replacement for typeid
  30. explicit DxilAddPixelHitInstrumentation() : ModulePass(ID) {}
  31. const char *getPassName() const override { return "DXIL Constant Color Mod"; }
  32. void applyOptions(PassOptions O) override;
  33. bool runOnModule(Module &M) override;
  34. };
  35. void DxilAddPixelHitInstrumentation::applyOptions(PassOptions O) {
  36. GetPassOptionBool(O, "force-early-z", &ForceEarlyZ, false);
  37. GetPassOptionBool(O, "add-pixel-cost", &AddPixelCost, false);
  38. GetPassOptionInt(O, "rt-width", &RTWidth, 0);
  39. GetPassOptionInt(O, "num-pixels", &NumPixels, 0);
  40. GetPassOptionInt(O, "sv-position-index", &SVPositionIndex, 0);
  41. }
  42. bool DxilAddPixelHitInstrumentation::runOnModule(Module &M) {
  43. // This pass adds instrumentation for pixel hit counting and pixel cost.
  44. DxilModule &DM = M.GetOrCreateDxilModule();
  45. LLVMContext &Ctx = M.getContext();
  46. OP *HlslOP = DM.GetOP();
  47. // ForceEarlyZ is incompatible with the discard function (the Z has to be
  48. // tested/written, and may be written before the shader even runs)
  49. if (ForceEarlyZ) {
  50. DM.m_ShaderFlags.SetForceEarlyDepthStencil(true);
  51. }
  52. hlsl::DxilSignature &InputSignature = DM.GetInputSignature();
  53. auto &InputElements = InputSignature.GetElements();
  54. unsigned SV_Position_ID;
  55. auto SV_Position =
  56. std::find_if(InputElements.begin(), InputElements.end(),
  57. [](const std::unique_ptr<DxilSignatureElement> &Element) {
  58. return Element->GetSemantic()->GetKind() ==
  59. hlsl::DXIL::SemanticKind::Position;
  60. });
  61. // SV_Position, if present, has to have full mask, so we needn't worry
  62. // about the shader having selected components that don't include x or y.
  63. // If not present, we add it.
  64. if (SV_Position == InputElements.end()) {
  65. auto SVPosition =
  66. llvm::make_unique<DxilSignatureElement>(DXIL::SigPointKind::PSIn);
  67. SVPosition->Initialize("Position", hlsl::CompType::getF32(),
  68. hlsl::DXIL::InterpolationMode::Linear, 1, 4,
  69. SVPositionIndex == -1 ? 0 : SVPositionIndex, 0);
  70. SVPosition->AppendSemanticIndex(0);
  71. SVPosition->SetSigPointKind(DXIL::SigPointKind::PSIn);
  72. SVPosition->SetKind(hlsl::DXIL::SemanticKind::Position);
  73. auto index = InputSignature.AppendElement(std::move(SVPosition));
  74. SV_Position_ID = InputElements[index]->GetID();
  75. } else {
  76. SV_Position_ID = SV_Position->get()->GetID();
  77. }
  78. auto EntryPointFunction = DM.GetEntryFunction();
  79. auto &EntryBlock = EntryPointFunction->getEntryBlock();
  80. CallInst *HandleForUAV;
  81. {
  82. IRBuilder<> Builder(
  83. dxilutil::FirstNonAllocaInsertionPt(DM.GetEntryFunction()));
  84. unsigned int UAVResourceHandle =
  85. static_cast<unsigned int>(DM.GetUAVs().size());
  86. // Set up a UAV with structure of a single int
  87. SmallVector<llvm::Type *, 1> Elements{Type::getInt32Ty(Ctx)};
  88. llvm::StructType *UAVStructTy =
  89. llvm::StructType::create(Elements, "class.RWStructuredBuffer");
  90. std::unique_ptr<DxilResource> pUAV = llvm::make_unique<DxilResource>();
  91. pUAV->SetGlobalName("PIX_CountUAVName");
  92. pUAV->SetGlobalSymbol(UndefValue::get(UAVStructTy->getPointerTo()));
  93. pUAV->SetID(UAVResourceHandle);
  94. pUAV->SetSpaceID(
  95. (unsigned int)-2); // This is the reserved-for-tools register space
  96. pUAV->SetSampleCount(1);
  97. pUAV->SetGloballyCoherent(false);
  98. pUAV->SetHasCounter(false);
  99. pUAV->SetCompType(CompType::getI32());
  100. pUAV->SetLowerBound(0);
  101. pUAV->SetRangeSize(1);
  102. pUAV->SetKind(DXIL::ResourceKind::RawBuffer);
  103. pUAV->SetRW(true);
  104. auto pAnnotation = DM.GetTypeSystem().GetStructAnnotation(UAVStructTy);
  105. if (pAnnotation == nullptr) {
  106. pAnnotation = DM.GetTypeSystem().AddStructAnnotation(UAVStructTy);
  107. pAnnotation->GetFieldAnnotation(0).SetCBufferOffset(0);
  108. pAnnotation->GetFieldAnnotation(0).SetCompType(
  109. hlsl::DXIL::ComponentType::I32);
  110. pAnnotation->GetFieldAnnotation(0).SetFieldName("count");
  111. }
  112. ID = DM.AddUAV(std::move(pUAV));
  113. assert((unsigned)ID == UAVResourceHandle);
  114. // Create handle for the newly-added UAV
  115. Function *CreateHandleOpFunc =
  116. HlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(Ctx));
  117. Constant *CreateHandleOpcodeArg =
  118. HlslOP->GetU32Const((unsigned)DXIL::OpCode::CreateHandle);
  119. Constant *UAVArg = HlslOP->GetI8Const(
  120. static_cast<std::underlying_type<DxilResourceBase::Class>::type>(
  121. DXIL::ResourceClass::UAV));
  122. Constant *MetaDataArg =
  123. HlslOP->GetU32Const(ID); // position of the metadata record in the
  124. // corresponding metadata list
  125. Constant *IndexArg = HlslOP->GetU32Const(0); //
  126. Constant *FalseArg =
  127. HlslOP->GetI1Const(0); // non-uniform resource index: false
  128. HandleForUAV = Builder.CreateCall(
  129. CreateHandleOpFunc,
  130. {CreateHandleOpcodeArg, UAVArg, MetaDataArg, IndexArg, FalseArg},
  131. "PIX_CountUAV_Handle");
  132. DM.ReEmitDxilResources();
  133. }
  134. // todo: is it a reasonable assumption that there will be a "Ret" in the entry
  135. // block, and that these are the only points from which the shader can exit
  136. // (except for a pixel-kill?)
  137. auto &Instructions = EntryBlock.getInstList();
  138. auto It = Instructions.begin();
  139. while (It != Instructions.end()) {
  140. auto ThisInstruction = It++;
  141. LlvmInst_Ret Ret(ThisInstruction);
  142. if (Ret) {
  143. // Check that there is at least one instruction preceding the Ret (no need
  144. // to instrument it if there isn't)
  145. if (ThisInstruction->getPrevNode() != nullptr) {
  146. // Start adding instructions right before the Ret:
  147. IRBuilder<> Builder(ThisInstruction);
  148. // ------------------------------------------------------------------------------------------------------------
  149. // Generate instructions to increment (by one) a UAV value corresponding
  150. // to the pixel currently being rendered
  151. // ------------------------------------------------------------------------------------------------------------
  152. // Useful constants
  153. Constant *Zero32Arg = HlslOP->GetU32Const(0);
  154. Constant *Zero8Arg = HlslOP->GetI8Const(0);
  155. Constant *One32Arg = HlslOP->GetU32Const(1);
  156. Constant *One8Arg = HlslOP->GetI8Const(1);
  157. UndefValue *UndefArg = UndefValue::get(Type::getInt32Ty(Ctx));
  158. Constant *NumPixelsByteOffsetArg = HlslOP->GetU32Const(NumPixels * 4);
  159. // Step 1: Convert SV_POSITION to UINT
  160. Value *XAsInt;
  161. Value *YAsInt;
  162. {
  163. auto LoadInputOpFunc =
  164. HlslOP->GetOpFunc(DXIL::OpCode::LoadInput, Type::getFloatTy(Ctx));
  165. Constant *LoadInputOpcode =
  166. HlslOP->GetU32Const((unsigned)DXIL::OpCode::LoadInput);
  167. Constant *SV_Pos_ID = HlslOP->GetU32Const(SV_Position_ID);
  168. auto XPos =
  169. Builder.CreateCall(LoadInputOpFunc,
  170. {LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
  171. Zero8Arg /*column*/, UndefArg},
  172. "XPos");
  173. auto YPos =
  174. Builder.CreateCall(LoadInputOpFunc,
  175. {LoadInputOpcode, SV_Pos_ID, Zero32Arg /*row*/,
  176. One8Arg /*column*/, UndefArg},
  177. "YPos");
  178. XAsInt = Builder.CreateCast(Instruction::CastOps::FPToUI, XPos,
  179. Type::getInt32Ty(Ctx), "XIndex");
  180. YAsInt = Builder.CreateCast(Instruction::CastOps::FPToUI, YPos,
  181. Type::getInt32Ty(Ctx), "YIndex");
  182. }
  183. // Step 2: Calculate pixel index
  184. Value *Index;
  185. {
  186. Constant *RTWidthArg = HlslOP->GetI32Const(RTWidth);
  187. auto YOffset = Builder.CreateMul(YAsInt, RTWidthArg, "YOffset");
  188. auto Elementoffset =
  189. Builder.CreateAdd(XAsInt, YOffset, "ElementOffset");
  190. Index = Builder.CreateMul(Elementoffset, HlslOP->GetU32Const(4),
  191. "ByteIndex");
  192. }
  193. // Insert the UAV increment instruction:
  194. Function *AtomicOpFunc =
  195. HlslOP->GetOpFunc(OP::OpCode::AtomicBinOp, Type::getInt32Ty(Ctx));
  196. Constant *AtomicBinOpcode =
  197. HlslOP->GetU32Const((unsigned)OP::OpCode::AtomicBinOp);
  198. Constant *AtomicAdd =
  199. HlslOP->GetU32Const((unsigned)DXIL::AtomicBinOpCode::Add);
  200. {
  201. (void)Builder.CreateCall(
  202. AtomicOpFunc,
  203. {
  204. AtomicBinOpcode, // i32, ; opcode
  205. HandleForUAV, // %dx.types.Handle, ; resource handle
  206. AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD,
  207. // AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
  208. Index, // i32, ; coordinate c0: byte offset
  209. UndefArg, // i32, ; coordinate c1 (unused)
  210. UndefArg, // i32, ; coordinate c2 (unused)
  211. One32Arg // i32); increment value
  212. },
  213. "UAVIncResult");
  214. }
  215. if (AddPixelCost) {
  216. // ------------------------------------------------------------------------------------------------------------
  217. // Generate instructions to increment a value corresponding to the
  218. // current pixel in the second half of the UAV, by an amount
  219. // proportional to the estimated average cost of each pixel in the
  220. // current draw call.
  221. // ------------------------------------------------------------------------------------------------------------
  222. // Step 1: Retrieve weight value from UAV; it will be placed after the
  223. // range we're writing to
  224. Value *Weight;
  225. {
  226. Function *LoadWeight = HlslOP->GetOpFunc(OP::OpCode::BufferLoad,
  227. Type::getInt32Ty(Ctx));
  228. Constant *LoadWeightOpcode =
  229. HlslOP->GetU32Const((unsigned)DXIL::OpCode::BufferLoad);
  230. Constant *OffsetIntoUAV = HlslOP->GetU32Const(NumPixels * 2 * 4);
  231. auto WeightStruct = Builder.CreateCall(
  232. LoadWeight,
  233. {
  234. LoadWeightOpcode, // i32 opcode
  235. HandleForUAV, // %dx.types.Handle, ; resource handle
  236. OffsetIntoUAV, // i32 c0: byte offset
  237. UndefArg // i32 c1: unused
  238. },
  239. "WeightStruct");
  240. Weight = Builder.CreateExtractValue(
  241. WeightStruct, static_cast<uint64_t>(0LL), "Weight");
  242. }
  243. // Step 2: Update write position ("Index") to second half of the UAV
  244. auto OffsetIndex = Builder.CreateAdd(Index, NumPixelsByteOffsetArg,
  245. "OffsetByteIndex");
  246. // Step 3: Increment UAV value by the weight
  247. (void)Builder.CreateCall(
  248. AtomicOpFunc,
  249. {
  250. AtomicBinOpcode, // i32, ; opcode
  251. HandleForUAV, // %dx.types.Handle, ; resource handle
  252. AtomicAdd, // i32, ; binary operation code : EXCHANGE, IADD,
  253. // AND, OR, XOR, IMIN, IMAX, UMIN, UMAX
  254. OffsetIndex, // i32, ; coordinate c0: byte offset
  255. UndefArg, // i32, ; coordinate c1 (unused)
  256. UndefArg, // i32, ; coordinate c2 (unused)
  257. Weight // i32); increment value
  258. },
  259. "UAVIncResult2");
  260. }
  261. }
  262. }
  263. }
  264. bool Modified = false;
  265. return Modified;
  266. }
  267. char DxilAddPixelHitInstrumentation::ID = 0;
  268. ModulePass *llvm::createDxilAddPixelHitInstrumentationPass() {
  269. return new DxilAddPixelHitInstrumentation();
  270. }
  271. INITIALIZE_PASS(DxilAddPixelHitInstrumentation,
  272. "hlsl-dxil-add-pixel-hit-instrmentation",
  273. "DXIL Count completed PS invocations and costs", false, false)