swr: [rasterizer jitter] cleanup supporting different llvm versions
[mesa.git] / src / gallium / drivers / swr / rasterizer / jitter / streamout_jit.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file streamout_jit.cpp
24 *
25 * @brief Implementation of the streamout jitter
26 *
27 * Notes:
28 *
29 ******************************************************************************/
30 #include "jit_api.h"
31 #include "streamout_jit.h"
32 #include "builder.h"
33 #include "state_llvm.h"
34 #include "llvm/IR/DataLayout.h"
35
36 #include <sstream>
37 #include <unordered_set>
38
39 //////////////////////////////////////////////////////////////////////////
40 /// Interface to Jitting a fetch shader
41 //////////////////////////////////////////////////////////////////////////
42 struct StreamOutJit : public Builder
43 {
44 StreamOutJit(JitManager* pJitMgr) : Builder(pJitMgr){};
45
46 // returns pointer to SWR_STREAMOUT_BUFFER
47 Value* getSOBuffer(Value* pSoCtx, uint32_t buffer)
48 {
49 return LOAD(pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_pBuffer, buffer });
50 }
51
52
53 //////////////////////////////////////////////////////////////////////////
54 // @brief checks if streamout buffer is oob
55 // @return <i1> true/false
56 Value* oob(const STREAMOUT_COMPILE_STATE& state, Value* pSoCtx, uint32_t buffer)
57 {
58 Value* returnMask = C(false);
59
60 Value* pBuf = getSOBuffer(pSoCtx, buffer);
61
62 // load enable
63 // @todo bool data types should generate <i1> llvm type
64 Value* enabled = TRUNC(LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_enable }), IRB()->getInt1Ty());
65
66 // load buffer size
67 Value* bufferSize = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_bufferSize });
68
69 // load current streamOffset
70 Value* streamOffset = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_streamOffset });
71
72 // load buffer pitch
73 Value* pitch = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_pitch });
74
75 // buffer is considered oob if in use in a decl but not enabled
76 returnMask = OR(returnMask, NOT(enabled));
77
78 // buffer is oob if cannot fit a prims worth of verts
79 Value* newOffset = ADD(streamOffset, MUL(pitch, C(state.numVertsPerPrim)));
80 returnMask = OR(returnMask, ICMP_SGT(newOffset, bufferSize));
81
82 return returnMask;
83 }
84
85
86 //////////////////////////////////////////////////////////////////////////
87 // @brief converts scalar bitmask to <4 x i32> suitable for shuffle vector,
88 // packing the active mask bits
89 // ex. bitmask 0011 -> (0, 1, 0, 0)
90 // bitmask 1000 -> (3, 0, 0, 0)
91 // bitmask 1100 -> (2, 3, 0, 0)
92 Value* PackMask(uint32_t bitmask)
93 {
94 std::vector<Constant*> indices(4, C(0));
95 DWORD index;
96 uint32_t elem = 0;
97 while (_BitScanForward(&index, bitmask))
98 {
99 indices[elem++] = C((int)index);
100 bitmask &= ~(1 << index);
101 }
102
103 return ConstantVector::get(indices);
104 }
105
106 //////////////////////////////////////////////////////////////////////////
107 // @brief convert scalar bitmask to <4xfloat> bitmask
108 Value* ToMask(uint32_t bitmask)
109 {
110 std::vector<Constant*> indices;
111 for (uint32_t i = 0; i < 4; ++i)
112 {
113 if (bitmask & (1 << i))
114 {
115 indices.push_back(C(-1.0f));
116 }
117 else
118 {
119 indices.push_back(C(0.0f));
120 }
121 }
122 return ConstantVector::get(indices);
123 }
124
125 //////////////////////////////////////////////////////////////////////////
126 // @brief processes a single decl from the streamout stream. Reads 4 components from the input
127 // stream and writes N components to the output buffer given the componentMask or if
128 // a hole, just increments the buffer pointer
129 // @param pStream - pointer to current attribute
130 // @param pOutBuffers - pointers to the current location of each output buffer
131 // @param decl - input decl
132 void buildDecl(Value* pStream, Value* pOutBuffers[4], const STREAMOUT_DECL& decl)
133 {
134 // @todo add this to x86 macros
135 Function* maskStore = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::x86_avx_maskstore_ps);
136
137 uint32_t numComponents = _mm_popcnt_u32(decl.componentMask);
138 uint32_t packedMask = (1 << numComponents) - 1;
139 if (!decl.hole)
140 {
141 // increment stream pointer to correct slot
142 Value* pAttrib = GEP(pStream, C(4 * decl.attribSlot));
143
144 // load 4 components from stream
145 Type* simd4Ty = VectorType::get(IRB()->getFloatTy(), 4);
146 Type* simd4PtrTy = PointerType::get(simd4Ty, 0);
147 pAttrib = BITCAST(pAttrib, simd4PtrTy);
148 Value *vattrib = LOAD(pAttrib);
149
150 // shuffle/pack enabled components
151 Value* vpackedAttrib = VSHUFFLE(vattrib, vattrib, PackMask(decl.componentMask));
152
153 // store to output buffer
154 // cast SO buffer to i8*, needed by maskstore
155 Value* pOut = BITCAST(pOutBuffers[decl.bufferIndex], PointerType::get(mInt8Ty, 0));
156
157 // cast input to <4xfloat>
158 Value* src = BITCAST(vpackedAttrib, simd4Ty);
159 CALL(maskStore, {pOut, ToMask(packedMask), src});
160 }
161
162 // increment SO buffer
163 pOutBuffers[decl.bufferIndex] = GEP(pOutBuffers[decl.bufferIndex], C(numComponents));
164 }
165
166 //////////////////////////////////////////////////////////////////////////
167 // @brief builds a single vertex worth of data for the given stream
168 // @param streamState - state for this stream
169 // @param pCurVertex - pointer to src stream vertex data
170 // @param pOutBuffer - pointers to up to 4 SO buffers
171 void buildVertex(const STREAMOUT_STREAM& streamState, Value* pCurVertex, Value* pOutBuffer[4])
172 {
173 for (uint32_t d = 0; d < streamState.numDecls; ++d)
174 {
175 const STREAMOUT_DECL& decl = streamState.decl[d];
176 buildDecl(pCurVertex, pOutBuffer, decl);
177 }
178 }
179
180 void buildStream(const STREAMOUT_COMPILE_STATE& state, const STREAMOUT_STREAM& streamState, Value* pSoCtx, BasicBlock* returnBB, Function* soFunc)
181 {
182 // get list of active SO buffers
183 std::unordered_set<uint32_t> activeSOBuffers;
184 for (uint32_t d = 0; d < streamState.numDecls; ++d)
185 {
186 const STREAMOUT_DECL& decl = streamState.decl[d];
187 activeSOBuffers.insert(decl.bufferIndex);
188 }
189
190 // always increment numPrimStorageNeeded
191 Value *numPrimStorageNeeded = LOAD(pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_numPrimStorageNeeded });
192 numPrimStorageNeeded = ADD(numPrimStorageNeeded, C(1));
193 STORE(numPrimStorageNeeded, pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_numPrimStorageNeeded });
194
195 // check OOB on active SO buffers. If any buffer is out of bound, don't write
196 // the primitive to any buffer
197 Value* oobMask = C(false);
198 for (uint32_t buffer : activeSOBuffers)
199 {
200 oobMask = OR(oobMask, oob(state, pSoCtx, buffer));
201 }
202
203 BasicBlock* validBB = BasicBlock::Create(JM()->mContext, "valid", soFunc);
204
205 // early out if OOB
206 COND_BR(oobMask, returnBB, validBB);
207
208 IRB()->SetInsertPoint(validBB);
209
210 Value* numPrimsWritten = LOAD(pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_numPrimsWritten });
211 numPrimsWritten = ADD(numPrimsWritten, C(1));
212 STORE(numPrimsWritten, pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_numPrimsWritten });
213
214 // compute start pointer for each output buffer
215 Value* pOutBuffer[4];
216 Value* pOutBufferStartVertex[4];
217 Value* outBufferPitch[4];
218 for (uint32_t b: activeSOBuffers)
219 {
220 Value* pBuf = getSOBuffer(pSoCtx, b);
221 Value* pData = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_pBuffer });
222 Value* streamOffset = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_streamOffset });
223 pOutBuffer[b] = GEP(pData, streamOffset);
224 pOutBufferStartVertex[b] = pOutBuffer[b];
225
226 outBufferPitch[b] = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_pitch });
227 }
228
229 // loop over the vertices of the prim
230 Value* pStreamData = LOAD(pSoCtx, { 0, SWR_STREAMOUT_CONTEXT_pPrimData });
231 for (uint32_t v = 0; v < state.numVertsPerPrim; ++v)
232 {
233 buildVertex(streamState, pStreamData, pOutBuffer);
234
235 // increment stream and output buffer pointers
236 // stream verts are always 32*4 dwords apart
237 pStreamData = GEP(pStreamData, C(KNOB_NUM_ATTRIBUTES * 4));
238
239 // output buffers offset using pitch in buffer state
240 for (uint32_t b : activeSOBuffers)
241 {
242 pOutBufferStartVertex[b] = GEP(pOutBufferStartVertex[b], outBufferPitch[b]);
243 pOutBuffer[b] = pOutBufferStartVertex[b];
244 }
245 }
246
247 // update each active buffer's streamOffset
248 for (uint32_t b : activeSOBuffers)
249 {
250 Value* pBuf = getSOBuffer(pSoCtx, b);
251 Value* streamOffset = LOAD(pBuf, { 0, SWR_STREAMOUT_BUFFER_streamOffset });
252 streamOffset = ADD(streamOffset, MUL(C(state.numVertsPerPrim), outBufferPitch[b]));
253 STORE(streamOffset, pBuf, { 0, SWR_STREAMOUT_BUFFER_streamOffset });
254 }
255 }
256
257 Function* Create(const STREAMOUT_COMPILE_STATE& state)
258 {
259 static std::size_t soNum = 0;
260
261 std::stringstream fnName("SOShader", std::ios_base::in | std::ios_base::out | std::ios_base::ate);
262 fnName << soNum++;
263
264 // SO function signature
265 // typedef void(__cdecl *PFN_SO_FUNC)(SWR_STREAMOUT_CONTEXT*)
266
267 std::vector<Type*> args{
268 PointerType::get(Gen_SWR_STREAMOUT_CONTEXT(JM()), 0), // SWR_STREAMOUT_CONTEXT*
269 };
270
271 FunctionType* fTy = FunctionType::get(IRB()->getVoidTy(), args, false);
272 Function* soFunc = Function::Create(fTy, GlobalValue::ExternalLinkage, fnName.str(), JM()->mpCurrentModule);
273
274 // create return basic block
275 BasicBlock* entry = BasicBlock::Create(JM()->mContext, "entry", soFunc);
276 BasicBlock* returnBB = BasicBlock::Create(JM()->mContext, "return", soFunc);
277
278 IRB()->SetInsertPoint(entry);
279
280 // arguments
281 auto argitr = soFunc->getArgumentList().begin();
282 Value* pSoCtx = &*argitr++;
283 pSoCtx->setName("pSoCtx");
284
285 const STREAMOUT_STREAM& streamState = state.stream;
286 buildStream(state, streamState, pSoCtx, returnBB, soFunc);
287
288 BR(returnBB);
289
290 IRB()->SetInsertPoint(returnBB);
291 RET_VOID();
292
293 JitManager::DumpToFile(soFunc, "SoFunc");
294
295 ::FunctionPassManager passes(JM()->mpCurrentModule);
296
297 passes.add(createBreakCriticalEdgesPass());
298 passes.add(createCFGSimplificationPass());
299 passes.add(createEarlyCSEPass());
300 passes.add(createPromoteMemoryToRegisterPass());
301 passes.add(createCFGSimplificationPass());
302 passes.add(createEarlyCSEPass());
303 passes.add(createInstructionCombiningPass());
304 passes.add(createInstructionSimplifierPass());
305 passes.add(createConstantPropagationPass());
306 passes.add(createSCCPPass());
307 passes.add(createAggressiveDCEPass());
308
309 passes.run(*soFunc);
310
311 JitManager::DumpToFile(soFunc, "SoFunc_optimized");
312
313 return soFunc;
314 }
315 };
316
317 //////////////////////////////////////////////////////////////////////////
318 /// @brief JITs from streamout shader IR
319 /// @param hJitMgr - JitManager handle
320 /// @param func - LLVM function IR
321 /// @return PFN_SO_FUNC - pointer to SOS function
322 PFN_SO_FUNC JitStreamoutFunc(HANDLE hJitMgr, const HANDLE hFunc)
323 {
324 const llvm::Function *func = (const llvm::Function*)hFunc;
325 JitManager* pJitMgr = reinterpret_cast<JitManager*>(hJitMgr);
326 PFN_SO_FUNC pfnStreamOut;
327 pfnStreamOut = (PFN_SO_FUNC)(pJitMgr->mpExec->getFunctionAddress(func->getName().str()));
328 // MCJIT finalizes modules the first time you JIT code from them. After finalized, you cannot add new IR to the module
329 pJitMgr->mIsModuleFinalized = true;
330
331 return pfnStreamOut;
332 }
333
334 //////////////////////////////////////////////////////////////////////////
335 /// @brief JIT compiles streamout shader
336 /// @param hJitMgr - JitManager handle
337 /// @param state - SO state to build function from
338 extern "C" PFN_SO_FUNC JITCALL JitCompileStreamout(HANDLE hJitMgr, const STREAMOUT_COMPILE_STATE& state)
339 {
340 JitManager* pJitMgr = reinterpret_cast<JitManager*>(hJitMgr);
341
342 STREAMOUT_COMPILE_STATE soState = state;
343 if (soState.offsetAttribs)
344 {
345 for (uint32_t i = 0; i < soState.stream.numDecls; ++i)
346 {
347 soState.stream.decl[i].attribSlot -= soState.offsetAttribs;
348 }
349 }
350
351 pJitMgr->SetupNewModule();
352
353 StreamOutJit theJit(pJitMgr);
354 HANDLE hFunc = theJit.Create(soState);
355
356 return JitStreamoutFunc(hJitMgr, hFunc);
357 }