swr: [rasterizer jitter] implement InstanceID/VertexID in fetch jit
[mesa.git] / src / gallium / drivers / swr / rasterizer / jitter / builder_misc.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 builder_misc.cpp
24 *
25 * @brief Implementation for miscellaneous builder functions
26 *
27 * Notes:
28 *
29 ******************************************************************************/
30 #include "builder.h"
31 #include "common/rdtsc_buckets.h"
32
33 #include "llvm/Support/DynamicLibrary.h"
34
35 void __cdecl CallPrint(const char* fmt, ...);
36
37 //////////////////////////////////////////////////////////////////////////
38 /// @brief Convert an IEEE 754 32-bit single precision float to an
39 /// 16 bit float with 5 exponent bits and a variable
40 /// number of mantissa bits.
41 /// @param val - 32-bit float
42 /// @todo Maybe move this outside of this file into a header?
43 static uint16_t Convert32To16Float(float val)
44 {
45 uint32_t sign, exp, mant;
46 uint32_t roundBits;
47
48 // Extract the sign, exponent, and mantissa
49 uint32_t uf = *(uint32_t*)&val;
50 sign = (uf & 0x80000000) >> 31;
51 exp = (uf & 0x7F800000) >> 23;
52 mant = uf & 0x007FFFFF;
53
54 // Check for out of range
55 if (std::isnan(val))
56 {
57 exp = 0x1F;
58 mant = 0x200;
59 sign = 1; // set the sign bit for NANs
60 }
61 else if (std::isinf(val))
62 {
63 exp = 0x1f;
64 mant = 0x0;
65 }
66 else if (exp > (0x70 + 0x1E)) // Too big to represent -> max representable value
67 {
68 exp = 0x1E;
69 mant = 0x3FF;
70 }
71 else if ((exp <= 0x70) && (exp >= 0x66)) // It's a denorm
72 {
73 mant |= 0x00800000;
74 for (; exp <= 0x70; mant >>= 1, exp++)
75 ;
76 exp = 0;
77 mant = mant >> 13;
78 }
79 else if (exp < 0x66) // Too small to represent -> Zero
80 {
81 exp = 0;
82 mant = 0;
83 }
84 else
85 {
86 // Saves bits that will be shifted off for rounding
87 roundBits = mant & 0x1FFFu;
88 // convert exponent and mantissa to 16 bit format
89 exp = exp - 0x70;
90 mant = mant >> 13;
91
92 // Essentially RTZ, but round up if off by only 1 lsb
93 if (roundBits == 0x1FFFu)
94 {
95 mant++;
96 // check for overflow
97 if ((mant & 0xC00u) != 0)
98 exp++;
99 // make sure only the needed bits are used
100 mant &= 0x3FF;
101 }
102 }
103
104 uint32_t tmpVal = (sign << 15) | (exp << 10) | mant;
105 return (uint16_t)tmpVal;
106 }
107
108 //////////////////////////////////////////////////////////////////////////
109 /// @brief Convert an IEEE 754 16-bit float to an 32-bit single precision
110 /// float
111 /// @param val - 16-bit float
112 /// @todo Maybe move this outside of this file into a header?
113 static float ConvertSmallFloatTo32(UINT val)
114 {
115 UINT result;
116 if ((val & 0x7fff) == 0)
117 {
118 result = ((uint32_t)(val & 0x8000)) << 16;
119 }
120 else if ((val & 0x7c00) == 0x7c00)
121 {
122 result = ((val & 0x3ff) == 0) ? 0x7f800000 : 0x7fc00000;
123 result |= ((uint32_t)val & 0x8000) << 16;
124 }
125 else
126 {
127 uint32_t sign = (val & 0x8000) << 16;
128 uint32_t mant = (val & 0x3ff) << 13;
129 uint32_t exp = (val >> 10) & 0x1f;
130 if ((exp == 0) && (mant != 0)) // Adjust exponent and mantissa for denormals
131 {
132 mant <<= 1;
133 while (mant < (0x400 << 13))
134 {
135 exp--;
136 mant <<= 1;
137 }
138 mant &= (0x3ff << 13);
139 }
140 exp = ((exp - 15 + 127) & 0xff) << 23;
141 result = sign | exp | mant;
142 }
143
144 return *(float*)&result;
145 }
146
147 Constant *Builder::C(bool i)
148 {
149 return ConstantInt::get(IRB()->getInt1Ty(), (i ? 1 : 0));
150 }
151
152 Constant *Builder::C(char i)
153 {
154 return ConstantInt::get(IRB()->getInt8Ty(), i);
155 }
156
157 Constant *Builder::C(uint8_t i)
158 {
159 return ConstantInt::get(IRB()->getInt8Ty(), i);
160 }
161
162 Constant *Builder::C(int i)
163 {
164 return ConstantInt::get(IRB()->getInt32Ty(), i);
165 }
166
167 Constant *Builder::C(int64_t i)
168 {
169 return ConstantInt::get(IRB()->getInt64Ty(), i);
170 }
171
172 Constant *Builder::C(uint16_t i)
173 {
174 return ConstantInt::get(mInt16Ty,i);
175 }
176
177 Constant *Builder::C(uint32_t i)
178 {
179 return ConstantInt::get(IRB()->getInt32Ty(), i);
180 }
181
182 Constant *Builder::C(float i)
183 {
184 return ConstantFP::get(IRB()->getFloatTy(), i);
185 }
186
187 Constant *Builder::PRED(bool pred)
188 {
189 return ConstantInt::get(IRB()->getInt1Ty(), (pred ? 1 : 0));
190 }
191
192 Value *Builder::VIMMED1(int i)
193 {
194 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
195 }
196
197 Value *Builder::VIMMED1(uint32_t i)
198 {
199 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
200 }
201
202 Value *Builder::VIMMED1(float i)
203 {
204 return ConstantVector::getSplat(mVWidth, cast<ConstantFP>(C(i)));
205 }
206
207 Value *Builder::VIMMED1(bool i)
208 {
209 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
210 }
211
212 Value *Builder::VUNDEF_IPTR()
213 {
214 return UndefValue::get(VectorType::get(mInt32PtrTy,mVWidth));
215 }
216
217 Value *Builder::VUNDEF_I()
218 {
219 return UndefValue::get(VectorType::get(mInt32Ty, mVWidth));
220 }
221
222 Value *Builder::VUNDEF(Type *ty, uint32_t size)
223 {
224 return UndefValue::get(VectorType::get(ty, size));
225 }
226
227 Value *Builder::VUNDEF_F()
228 {
229 return UndefValue::get(VectorType::get(mFP32Ty, mVWidth));
230 }
231
232 Value *Builder::VUNDEF(Type* t)
233 {
234 return UndefValue::get(VectorType::get(t, mVWidth));
235 }
236
237 #if HAVE_LLVM == 0x306
238 Value *Builder::VINSERT(Value *vec, Value *val, uint64_t index)
239 {
240 return VINSERT(vec, val, C((int64_t)index));
241 }
242 #endif
243
244 Value *Builder::VBROADCAST(Value *src)
245 {
246 // check if src is already a vector
247 if (src->getType()->isVectorTy())
248 {
249 return src;
250 }
251
252 return VECTOR_SPLAT(mVWidth, src);
253 }
254
255 uint32_t Builder::IMMED(Value* v)
256 {
257 SWR_ASSERT(isa<ConstantInt>(v));
258 ConstantInt *pValConst = cast<ConstantInt>(v);
259 return pValConst->getZExtValue();
260 }
261
262 int32_t Builder::S_IMMED(Value* v)
263 {
264 SWR_ASSERT(isa<ConstantInt>(v));
265 ConstantInt *pValConst = cast<ConstantInt>(v);
266 return pValConst->getSExtValue();
267 }
268
269 Value *Builder::GEP(Value* ptr, const std::initializer_list<Value*> &indexList)
270 {
271 std::vector<Value*> indices;
272 for (auto i : indexList)
273 indices.push_back(i);
274 return GEPA(ptr, indices);
275 }
276
277 Value *Builder::GEP(Value* ptr, const std::initializer_list<uint32_t> &indexList)
278 {
279 std::vector<Value*> indices;
280 for (auto i : indexList)
281 indices.push_back(C(i));
282 return GEPA(ptr, indices);
283 }
284
285 LoadInst *Builder::LOAD(Value *basePtr, const std::initializer_list<uint32_t> &indices, const llvm::Twine& name)
286 {
287 std::vector<Value*> valIndices;
288 for (auto i : indices)
289 valIndices.push_back(C(i));
290 return LOAD(GEPA(basePtr, valIndices), name);
291 }
292
293 LoadInst *Builder::LOADV(Value *basePtr, const std::initializer_list<Value*> &indices, const llvm::Twine& name)
294 {
295 std::vector<Value*> valIndices;
296 for (auto i : indices)
297 valIndices.push_back(i);
298 return LOAD(GEPA(basePtr, valIndices), name);
299 }
300
301 StoreInst *Builder::STORE(Value *val, Value *basePtr, const std::initializer_list<uint32_t> &indices)
302 {
303 std::vector<Value*> valIndices;
304 for (auto i : indices)
305 valIndices.push_back(C(i));
306 return STORE(val, GEPA(basePtr, valIndices));
307 }
308
309 StoreInst *Builder::STOREV(Value *val, Value *basePtr, const std::initializer_list<Value*> &indices)
310 {
311 std::vector<Value*> valIndices;
312 for (auto i : indices)
313 valIndices.push_back(i);
314 return STORE(val, GEPA(basePtr, valIndices));
315 }
316
317 CallInst *Builder::CALL(Value *Callee, const std::initializer_list<Value*> &argsList)
318 {
319 std::vector<Value*> args;
320 for (auto arg : argsList)
321 args.push_back(arg);
322 return CALLA(Callee, args);
323 }
324
325 Value *Builder::VRCP(Value *va)
326 {
327 return FDIV(VIMMED1(1.0f), va); // 1 / a
328 }
329
330 Value *Builder::VPLANEPS(Value* vA, Value* vB, Value* vC, Value* &vX, Value* &vY)
331 {
332 Value* vOut = FMADDPS(vA, vX, vC);
333 vOut = FMADDPS(vB, vY, vOut);
334 return vOut;
335 }
336
337 //////////////////////////////////////////////////////////////////////////
338 /// @brief Generate an i32 masked load operation in LLVM IR. If not
339 /// supported on the underlying platform, emulate it with float masked load
340 /// @param src - base address pointer for the load
341 /// @param vMask - SIMD wide mask that controls whether to access memory load 0
342 Value *Builder::MASKLOADD(Value* src,Value* mask)
343 {
344 Value* vResult;
345 // use avx2 gather instruction is available
346 if(JM()->mArch.AVX2())
347 {
348 Function *func = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::x86_avx2_maskload_d_256);
349 vResult = CALL(func,{src,mask});
350 }
351 else
352 {
353 // maskload intrinsic expects integer mask operand in llvm >= 3.8
354 #if (LLVM_VERSION_MAJOR > 3) || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 8)
355 mask = BITCAST(mask,VectorType::get(mInt32Ty,mVWidth));
356 #else
357 mask = BITCAST(mask,VectorType::get(mFP32Ty,mVWidth));
358 #endif
359 Function *func = Intrinsic::getDeclaration(JM()->mpCurrentModule,Intrinsic::x86_avx_maskload_ps_256);
360 vResult = BITCAST(CALL(func,{src,mask}), VectorType::get(mInt32Ty,mVWidth));
361 }
362 return vResult;
363 }
364
365 //////////////////////////////////////////////////////////////////////////
366 /// @brief insert a JIT call to CallPrint
367 /// - outputs formatted string to both stdout and VS output window
368 /// - DEBUG builds only
369 /// Usage example:
370 /// PRINT("index %d = 0x%p\n",{C(lane), pIndex});
371 /// where C(lane) creates a constant value to print, and pIndex is the Value*
372 /// result from a GEP, printing out the pointer to memory
373 /// @param printStr - constant string to print, which includes format specifiers
374 /// @param printArgs - initializer list of Value*'s to print to std out
375 CallInst *Builder::PRINT(const std::string &printStr,const std::initializer_list<Value*> &printArgs)
376 {
377 // push the arguments to CallPrint into a vector
378 std::vector<Value*> printCallArgs;
379 // save room for the format string. we still need to modify it for vectors
380 printCallArgs.resize(1);
381
382 // search through the format string for special processing
383 size_t pos = 0;
384 std::string tempStr(printStr);
385 pos = tempStr.find('%', pos);
386 auto v = printArgs.begin();
387
388 while ((pos != std::string::npos) && (v != printArgs.end()))
389 {
390 Value* pArg = *v;
391 Type* pType = pArg->getType();
392
393 if (pType->isVectorTy())
394 {
395 Type* pContainedType = pType->getContainedType(0);
396
397 if (toupper(tempStr[pos + 1]) == 'X')
398 {
399 tempStr[pos] = '0';
400 tempStr[pos + 1] = 'x';
401 tempStr.insert(pos + 2, "%08X ");
402 pos += 7;
403
404 printCallArgs.push_back(VEXTRACT(pArg, C(0)));
405
406 std::string vectorFormatStr;
407 for (uint32_t i = 1; i < pType->getVectorNumElements(); ++i)
408 {
409 vectorFormatStr += "0x%08X ";
410 printCallArgs.push_back(VEXTRACT(pArg, C(i)));
411 }
412
413 tempStr.insert(pos, vectorFormatStr);
414 pos += vectorFormatStr.size();
415 }
416 else if ((tempStr[pos + 1] == 'f') && (pContainedType->isFloatTy()))
417 {
418 uint32_t i = 0;
419 for (; i < (pArg->getType()->getVectorNumElements()) - 1; i++)
420 {
421 tempStr.insert(pos, std::string("%f "));
422 pos += 3;
423 printCallArgs.push_back(FP_EXT(VEXTRACT(pArg, C(i)), Type::getDoubleTy(JM()->mContext)));
424 }
425 printCallArgs.push_back(FP_EXT(VEXTRACT(pArg, C(i)), Type::getDoubleTy(JM()->mContext)));
426 }
427 else if ((tempStr[pos + 1] == 'd') && (pContainedType->isIntegerTy()))
428 {
429 uint32_t i = 0;
430 for (; i < (pArg->getType()->getVectorNumElements()) - 1; i++)
431 {
432 tempStr.insert(pos, std::string("%d "));
433 pos += 3;
434 printCallArgs.push_back(VEXTRACT(pArg, C(i)));
435 }
436 printCallArgs.push_back(VEXTRACT(pArg, C(i)));
437 }
438 }
439 else
440 {
441 if (toupper(tempStr[pos + 1]) == 'X')
442 {
443 tempStr[pos] = '0';
444 tempStr.insert(pos + 1, "x%08");
445 printCallArgs.push_back(pArg);
446 pos += 3;
447 }
448 // for %f we need to cast float Values to doubles so that they print out correctly
449 else if ((tempStr[pos + 1] == 'f') && (pType->isFloatTy()))
450 {
451 printCallArgs.push_back(FP_EXT(pArg, Type::getDoubleTy(JM()->mContext)));
452 pos++;
453 }
454 else
455 {
456 printCallArgs.push_back(pArg);
457 }
458 }
459
460 // advance to the next arguement
461 v++;
462 pos = tempStr.find('%', ++pos);
463 }
464
465 // create global variable constant string
466 Constant *constString = ConstantDataArray::getString(JM()->mContext,tempStr,true);
467 GlobalVariable *gvPtr = new GlobalVariable(constString->getType(),true,GlobalValue::InternalLinkage,constString,"printStr");
468 JM()->mpCurrentModule->getGlobalList().push_back(gvPtr);
469
470 // get a pointer to the first character in the constant string array
471 std::vector<Constant*> geplist{C(0),C(0)};
472 #if HAVE_LLVM == 0x306
473 Constant *strGEP = ConstantExpr::getGetElementPtr(gvPtr,geplist,false);
474 #else
475 Constant *strGEP = ConstantExpr::getGetElementPtr(nullptr, gvPtr,geplist,false);
476 #endif
477
478 // insert the pointer to the format string in the argument vector
479 printCallArgs[0] = strGEP;
480
481 // get pointer to CallPrint function and insert decl into the module if needed
482 std::vector<Type*> args;
483 args.push_back(PointerType::get(mInt8Ty,0));
484 FunctionType* callPrintTy = FunctionType::get(Type::getVoidTy(JM()->mContext),args,true);
485 Function *callPrintFn = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("CallPrint", callPrintTy));
486
487 // if we haven't yet added the symbol to the symbol table
488 if((sys::DynamicLibrary::SearchForAddressOfSymbol("CallPrint")) == nullptr)
489 {
490 sys::DynamicLibrary::AddSymbol("CallPrint", (void *)&CallPrint);
491 }
492
493 // insert a call to CallPrint
494 return CALLA(callPrintFn,printCallArgs);
495 }
496
497 //////////////////////////////////////////////////////////////////////////
498 /// @brief Wrapper around PRINT with initializer list.
499 CallInst* Builder::PRINT(const std::string &printStr)
500 {
501 return PRINT(printStr, {});
502 }
503
504 //////////////////////////////////////////////////////////////////////////
505 /// @brief Generate a masked gather operation in LLVM IR. If not
506 /// supported on the underlying platform, emulate it with loads
507 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
508 /// @param pBase - Int8* base VB address pointer value
509 /// @param vIndices - SIMD wide value of VB byte offsets
510 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
511 /// @param scale - value to scale indices by
512 Value *Builder::GATHERPS(Value* vSrc, Value* pBase, Value* vIndices, Value* vMask, Value* scale)
513 {
514 Value* vGather;
515
516 // use avx2 gather instruction if available
517 if(JM()->mArch.AVX2())
518 {
519 // force mask to <N x float>, required by vgather
520 vMask = BITCAST(vMask, mSimdFP32Ty);
521 vGather = VGATHERPS(vSrc,pBase,vIndices,vMask,scale);
522 }
523 else
524 {
525 Value* pStack = STACKSAVE();
526
527 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
528 Value* vSrcPtr = ALLOCA(vSrc->getType());
529 STORE(vSrc, vSrcPtr);
530
531 vGather = VUNDEF_F();
532 Value *vScaleVec = VBROADCAST(Z_EXT(scale,mInt32Ty));
533 Value *vOffsets = MUL(vIndices,vScaleVec);
534 Value *mask = MASK(vMask);
535 for(uint32_t i = 0; i < mVWidth; ++i)
536 {
537 // single component byte index
538 Value *offset = VEXTRACT(vOffsets,C(i));
539 // byte pointer to component
540 Value *loadAddress = GEP(pBase,offset);
541 loadAddress = BITCAST(loadAddress,PointerType::get(mFP32Ty,0));
542 // pointer to the value to load if we're masking off a component
543 Value *maskLoadAddress = GEP(vSrcPtr,{C(0), C(i)});
544 Value *selMask = VEXTRACT(mask,C(i));
545 // switch in a safe address to load if we're trying to access a vertex
546 Value *validAddress = SELECT(selMask, loadAddress, maskLoadAddress);
547 Value *val = LOAD(validAddress);
548 vGather = VINSERT(vGather,val,C(i));
549 }
550 STACKRESTORE(pStack);
551 }
552
553 return vGather;
554 }
555
556 //////////////////////////////////////////////////////////////////////////
557 /// @brief Generate a masked gather operation in LLVM IR. If not
558 /// supported on the underlying platform, emulate it with loads
559 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
560 /// @param pBase - Int8* base VB address pointer value
561 /// @param vIndices - SIMD wide value of VB byte offsets
562 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
563 /// @param scale - value to scale indices by
564 Value *Builder::GATHERDD(Value* vSrc, Value* pBase, Value* vIndices, Value* vMask, Value* scale)
565 {
566 Value* vGather;
567
568 // use avx2 gather instruction if available
569 if(JM()->mArch.AVX2())
570 {
571 vGather = VGATHERDD(vSrc, pBase, vIndices, vMask, scale);
572 }
573 else
574 {
575 Value* pStack = STACKSAVE();
576
577 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
578 Value* vSrcPtr = ALLOCA(vSrc->getType());
579 STORE(vSrc, vSrcPtr);
580
581 vGather = VUNDEF_I();
582 Value *vScaleVec = VBROADCAST(Z_EXT(scale, mInt32Ty));
583 Value *vOffsets = MUL(vIndices, vScaleVec);
584 Value *mask = MASK(vMask);
585 for(uint32_t i = 0; i < mVWidth; ++i)
586 {
587 // single component byte index
588 Value *offset = VEXTRACT(vOffsets, C(i));
589 // byte pointer to component
590 Value *loadAddress = GEP(pBase, offset);
591 loadAddress = BITCAST(loadAddress, PointerType::get(mInt32Ty, 0));
592 // pointer to the value to load if we're masking off a component
593 Value *maskLoadAddress = GEP(vSrcPtr, {C(0), C(i)});
594 Value *selMask = VEXTRACT(mask, C(i));
595 // switch in a safe address to load if we're trying to access a vertex
596 Value *validAddress = SELECT(selMask, loadAddress, maskLoadAddress);
597 Value *val = LOAD(validAddress, C(0));
598 vGather = VINSERT(vGather, val, C(i));
599 }
600
601 STACKRESTORE(pStack);
602 }
603 return vGather;
604 }
605
606 //////////////////////////////////////////////////////////////////////////
607 /// @brief convert x86 <N x float> mask to llvm <N x i1> mask
608 Value* Builder::MASK(Value* vmask)
609 {
610 Value* src = BITCAST(vmask, mSimdInt32Ty);
611 return ICMP_SLT(src, VIMMED1(0));
612 }
613
614 //////////////////////////////////////////////////////////////////////////
615 /// @brief convert llvm <N x i1> mask to x86 <N x i32> mask
616 Value* Builder::VMASK(Value* mask)
617 {
618 return S_EXT(mask, mSimdInt32Ty);
619 }
620
621 //////////////////////////////////////////////////////////////////////////
622 /// @brief Generate a VPSHUFB operation in LLVM IR. If not
623 /// supported on the underlying platform, emulate it
624 /// @param a - 256bit SIMD(32x8bit) of 8bit integer values
625 /// @param b - 256bit SIMD(32x8bit) of 8bit integer mask values
626 /// Byte masks in lower 128 lane of b selects 8 bit values from lower
627 /// 128bits of a, and vice versa for the upper lanes. If the mask
628 /// value is negative, '0' is inserted.
629 Value *Builder::PSHUFB(Value* a, Value* b)
630 {
631 Value* res;
632 // use avx2 pshufb instruction if available
633 if(JM()->mArch.AVX2())
634 {
635 res = VPSHUFB(a, b);
636 }
637 else
638 {
639 Constant* cB = dyn_cast<Constant>(b);
640 // number of 8 bit elements in b
641 uint32_t numElms = cast<VectorType>(cB->getType())->getNumElements();
642 // output vector
643 Value* vShuf = UndefValue::get(VectorType::get(mInt8Ty, numElms));
644
645 // insert an 8 bit value from the high and low lanes of a per loop iteration
646 numElms /= 2;
647 for(uint32_t i = 0; i < numElms; i++)
648 {
649 ConstantInt* cLow128b = cast<ConstantInt>(cB->getAggregateElement(i));
650 ConstantInt* cHigh128b = cast<ConstantInt>(cB->getAggregateElement(i + numElms));
651
652 // extract values from constant mask
653 char valLow128bLane = (char)(cLow128b->getSExtValue());
654 char valHigh128bLane = (char)(cHigh128b->getSExtValue());
655
656 Value* insertValLow128b;
657 Value* insertValHigh128b;
658
659 // if the mask value is negative, insert a '0' in the respective output position
660 // otherwise, lookup the value at mask position (bits 3..0 of the respective mask byte) in a and insert in output vector
661 insertValLow128b = (valLow128bLane < 0) ? C((char)0) : VEXTRACT(a, C((valLow128bLane & 0xF)));
662 insertValHigh128b = (valHigh128bLane < 0) ? C((char)0) : VEXTRACT(a, C((valHigh128bLane & 0xF) + numElms));
663
664 vShuf = VINSERT(vShuf, insertValLow128b, i);
665 vShuf = VINSERT(vShuf, insertValHigh128b, (i + numElms));
666 }
667 res = vShuf;
668 }
669 return res;
670 }
671
672 //////////////////////////////////////////////////////////////////////////
673 /// @brief Generate a VPSHUFB operation (sign extend 8 8bit values to 32
674 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
675 /// @param a - 128bit SIMD lane(16x8bit) of 8bit integer values. Only
676 /// lower 8 values are used.
677 Value *Builder::PMOVSXBD(Value* a)
678 {
679 Value* res;
680 // use avx2 byte sign extend instruction if available
681 if(JM()->mArch.AVX2())
682 {
683 res = VPMOVSXBD(a);
684 }
685 else
686 {
687 // VPMOVSXBD output type
688 Type* v8x32Ty = VectorType::get(mInt32Ty, 8);
689 // Extract 8 values from 128bit lane and sign extend
690 res = S_EXT(VSHUFFLE(a, a, C<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty);
691 }
692 return res;
693 }
694
695 //////////////////////////////////////////////////////////////////////////
696 /// @brief Generate a VPSHUFB operation (sign extend 8 16bit values to 32
697 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
698 /// @param a - 128bit SIMD lane(8x16bit) of 16bit integer values.
699 Value *Builder::PMOVSXWD(Value* a)
700 {
701 Value* res;
702 // use avx2 word sign extend if available
703 if(JM()->mArch.AVX2())
704 {
705 res = VPMOVSXWD(a);
706 }
707 else
708 {
709 // VPMOVSXWD output type
710 Type* v8x32Ty = VectorType::get(mInt32Ty, 8);
711 // Extract 8 values from 128bit lane and sign extend
712 res = S_EXT(VSHUFFLE(a, a, C<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty);
713 }
714 return res;
715 }
716
717 //////////////////////////////////////////////////////////////////////////
718 /// @brief Generate a VPERMD operation (shuffle 32 bit integer values
719 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
720 /// platform, emulate it
721 /// @param a - 256bit SIMD lane(8x32bit) of integer values.
722 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
723 Value *Builder::PERMD(Value* a, Value* idx)
724 {
725 Value* res;
726 // use avx2 permute instruction if available
727 if(JM()->mArch.AVX2())
728 {
729 // llvm 3.6.0 swapped the order of the args to vpermd
730 res = VPERMD(idx, a);
731 }
732 else
733 {
734 if (isa<Constant>(idx))
735 {
736 res = VSHUFFLE(a, a, idx);
737 }
738 else
739 {
740 res = VUNDEF_I();
741 for (uint32_t l = 0; l < JM()->mVWidth; ++l)
742 {
743 Value* pIndex = VEXTRACT(idx, C(l));
744 Value* pVal = VEXTRACT(a, pIndex);
745 res = VINSERT(res, pVal, C(l));
746 }
747 }
748 }
749 return res;
750 }
751
752 //////////////////////////////////////////////////////////////////////////
753 /// @brief Generate a VPERMPS operation (shuffle 32 bit float values
754 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
755 /// platform, emulate it
756 /// @param a - 256bit SIMD lane(8x32bit) of float values.
757 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
758 Value *Builder::PERMPS(Value* a, Value* idx)
759 {
760 Value* res;
761 // use avx2 permute instruction if available
762 if (JM()->mArch.AVX2())
763 {
764 // llvm 3.6.0 swapped the order of the args to vpermd
765 res = VPERMPS(idx, a);
766 }
767 else
768 {
769 if (isa<Constant>(idx))
770 {
771 res = VSHUFFLE(a, a, idx);
772 }
773 else
774 {
775 res = VUNDEF_F();
776 for (uint32_t l = 0; l < JM()->mVWidth; ++l)
777 {
778 Value* pIndex = VEXTRACT(idx, C(l));
779 Value* pVal = VEXTRACT(a, pIndex);
780 res = VINSERT(res, pVal, C(l));
781 }
782 }
783 }
784
785 return res;
786 }
787
788 //////////////////////////////////////////////////////////////////////////
789 /// @brief Generate a VCVTPH2PS operation (float16->float32 conversion)
790 /// in LLVM IR. If not supported on the underlying platform, emulate it
791 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
792 Value *Builder::CVTPH2PS(Value* a)
793 {
794 if (JM()->mArch.F16C())
795 {
796 return VCVTPH2PS(a);
797 }
798 else
799 {
800 FunctionType* pFuncTy = FunctionType::get(mFP32Ty, mInt16Ty);
801 Function* pCvtPh2Ps = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("ConvertSmallFloatTo32", pFuncTy));
802
803 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertSmallFloatTo32") == nullptr)
804 {
805 sys::DynamicLibrary::AddSymbol("ConvertSmallFloatTo32", (void *)&ConvertSmallFloatTo32);
806 }
807
808 Value* pResult = UndefValue::get(mSimdFP32Ty);
809 for (uint32_t i = 0; i < mVWidth; ++i)
810 {
811 Value* pSrc = VEXTRACT(a, C(i));
812 Value* pConv = CALL(pCvtPh2Ps, std::initializer_list<Value*>{pSrc});
813 pResult = VINSERT(pResult, pConv, C(i));
814 }
815
816 return pResult;
817 }
818 }
819
820 //////////////////////////////////////////////////////////////////////////
821 /// @brief Generate a VCVTPS2PH operation (float32->float16 conversion)
822 /// in LLVM IR. If not supported on the underlying platform, emulate it
823 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
824 Value *Builder::CVTPS2PH(Value* a, Value* rounding)
825 {
826 if (JM()->mArch.F16C())
827 {
828 return VCVTPS2PH(a, rounding);
829 }
830 else
831 {
832 // call scalar C function for now
833 FunctionType* pFuncTy = FunctionType::get(mInt16Ty, mFP32Ty);
834 Function* pCvtPs2Ph = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("Convert32To16Float", pFuncTy));
835
836 if (sys::DynamicLibrary::SearchForAddressOfSymbol("Convert32To16Float") == nullptr)
837 {
838 sys::DynamicLibrary::AddSymbol("Convert32To16Float", (void *)&Convert32To16Float);
839 }
840
841 Value* pResult = UndefValue::get(mSimdInt16Ty);
842 for (uint32_t i = 0; i < mVWidth; ++i)
843 {
844 Value* pSrc = VEXTRACT(a, C(i));
845 Value* pConv = CALL(pCvtPs2Ph, std::initializer_list<Value*>{pSrc});
846 pResult = VINSERT(pResult, pConv, C(i));
847 }
848
849 return pResult;
850 }
851 }
852
853 Value *Builder::PMAXSD(Value* a, Value* b)
854 {
855 if (JM()->mArch.AVX2())
856 {
857 return VPMAXSD(a, b);
858 }
859 else
860 {
861 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
862 Function* pmaxsd = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::x86_sse41_pmaxsd);
863
864 // low 128
865 Value* aLo = VEXTRACTI128(a, C((uint8_t)0));
866 Value* bLo = VEXTRACTI128(b, C((uint8_t)0));
867 Value* resLo = CALL(pmaxsd, {aLo, bLo});
868
869 // high 128
870 Value* aHi = VEXTRACTI128(a, C((uint8_t)1));
871 Value* bHi = VEXTRACTI128(b, C((uint8_t)1));
872 Value* resHi = CALL(pmaxsd, {aHi, bHi});
873
874 // combine
875 Value* result = VINSERTI128(VUNDEF_I(), resLo, C((uint8_t)0));
876 result = VINSERTI128(result, resHi, C((uint8_t)1));
877
878 return result;
879 }
880 }
881
882 Value *Builder::PMINSD(Value* a, Value* b)
883 {
884 if (JM()->mArch.AVX2())
885 {
886 return VPMINSD(a, b);
887 }
888 else
889 {
890 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
891 Function* pminsd = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::x86_sse41_pminsd);
892
893 // low 128
894 Value* aLo = VEXTRACTI128(a, C((uint8_t)0));
895 Value* bLo = VEXTRACTI128(b, C((uint8_t)0));
896 Value* resLo = CALL(pminsd, {aLo, bLo});
897
898 // high 128
899 Value* aHi = VEXTRACTI128(a, C((uint8_t)1));
900 Value* bHi = VEXTRACTI128(b, C((uint8_t)1));
901 Value* resHi = CALL(pminsd, {aHi, bHi});
902
903 // combine
904 Value* result = VINSERTI128(VUNDEF_I(), resLo, C((uint8_t)0));
905 result = VINSERTI128(result, resHi, C((uint8_t)1));
906
907 return result;
908 }
909 }
910
911 void Builder::Gather4(const SWR_FORMAT format, Value* pSrcBase, Value* byteOffsets,
912 Value* mask, Value* vGatherComponents[], bool bPackedOutput)
913 {
914 const SWR_FORMAT_INFO &info = GetFormatInfo(format);
915 if(info.type[0] == SWR_TYPE_FLOAT && info.bpc[0] == 32)
916 {
917 // ensure our mask is the correct type
918 mask = BITCAST(mask, mSimdFP32Ty);
919 GATHER4PS(info, pSrcBase, byteOffsets, mask, vGatherComponents, bPackedOutput);
920 }
921 else
922 {
923 // ensure our mask is the correct type
924 mask = BITCAST(mask, mSimdInt32Ty);
925 GATHER4DD(info, pSrcBase, byteOffsets, mask, vGatherComponents, bPackedOutput);
926 }
927 }
928
929 void Builder::GATHER4PS(const SWR_FORMAT_INFO &info, Value* pSrcBase, Value* byteOffsets,
930 Value* mask, Value* vGatherComponents[], bool bPackedOutput)
931 {
932 switch(info.bpp / info.numComps)
933 {
934 case 16:
935 {
936 Value* vGatherResult[2];
937 Value *vMask;
938
939 // TODO: vGatherMaskedVal
940 Value* vGatherMaskedVal = VIMMED1((float)0);
941
942 // always have at least one component out of x or y to fetch
943
944 // save mask as it is zero'd out after each gather
945 vMask = mask;
946
947 vGatherResult[0] = GATHERPS(vGatherMaskedVal, pSrcBase, byteOffsets, vMask, C((char)1));
948 // e.g. result of first 8x32bit integer gather for 16bit components
949 // 256i - 0 1 2 3 4 5 6 7
950 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
951 //
952
953 // if we have at least one component out of x or y to fetch
954 if(info.numComps > 2)
955 {
956 // offset base to the next components(zw) in the vertex to gather
957 pSrcBase = GEP(pSrcBase, C((char)4));
958 vMask = mask;
959
960 vGatherResult[1] = GATHERPS(vGatherMaskedVal, pSrcBase, byteOffsets, vMask, C((char)1));
961 // e.g. result of second 8x32bit integer gather for 16bit components
962 // 256i - 0 1 2 3 4 5 6 7
963 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
964 //
965 }
966 else
967 {
968 vGatherResult[1] = vGatherMaskedVal;
969 }
970
971 // Shuffle gathered components into place, each row is a component
972 Shuffle16bpcGather4(info, vGatherResult, vGatherComponents, bPackedOutput);
973 }
974 break;
975 case 32:
976 {
977 // apply defaults
978 for (uint32_t i = 0; i < 4; ++i)
979 {
980 vGatherComponents[i] = VIMMED1(*(float*)&info.defaults[i]);
981 }
982
983 for(uint32_t i = 0; i < info.numComps; i++)
984 {
985 uint32_t swizzleIndex = info.swizzle[i];
986
987 // save mask as it is zero'd out after each gather
988 Value *vMask = mask;
989
990 // Gather a SIMD of components
991 vGatherComponents[swizzleIndex] = GATHERPS(vGatherComponents[swizzleIndex], pSrcBase, byteOffsets, vMask, C((char)1));
992
993 // offset base to the next component to gather
994 pSrcBase = GEP(pSrcBase, C((char)4));
995 }
996 }
997 break;
998 default:
999 SWR_ASSERT(0, "Invalid float format");
1000 break;
1001 }
1002 }
1003
1004 void Builder::GATHER4DD(const SWR_FORMAT_INFO &info, Value* pSrcBase, Value* byteOffsets,
1005 Value* mask, Value* vGatherComponents[], bool bPackedOutput)
1006 {
1007 switch (info.bpp / info.numComps)
1008 {
1009 case 8:
1010 {
1011 Value* vGatherMaskedVal = VIMMED1((int32_t)0);
1012 Value* vGatherResult = GATHERDD(vGatherMaskedVal, pSrcBase, byteOffsets, mask, C((char)1));
1013 // e.g. result of an 8x32bit integer gather for 8bit components
1014 // 256i - 0 1 2 3 4 5 6 7
1015 // xyzw xyzw xyzw xyzw xyzw xyzw xyzw xyzw
1016
1017 Shuffle8bpcGather4(info, vGatherResult, vGatherComponents, bPackedOutput);
1018 }
1019 break;
1020 case 16:
1021 {
1022 Value* vGatherResult[2];
1023 Value *vMask;
1024
1025 // TODO: vGatherMaskedVal
1026 Value* vGatherMaskedVal = VIMMED1((int32_t)0);
1027
1028 // always have at least one component out of x or y to fetch
1029
1030 // save mask as it is zero'd out after each gather
1031 vMask = mask;
1032
1033 vGatherResult[0] = GATHERDD(vGatherMaskedVal, pSrcBase, byteOffsets, vMask, C((char)1));
1034 // e.g. result of first 8x32bit integer gather for 16bit components
1035 // 256i - 0 1 2 3 4 5 6 7
1036 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
1037 //
1038
1039 // if we have at least one component out of x or y to fetch
1040 if(info.numComps > 2)
1041 {
1042 // offset base to the next components(zw) in the vertex to gather
1043 pSrcBase = GEP(pSrcBase, C((char)4));
1044 vMask = mask;
1045
1046 vGatherResult[1] = GATHERDD(vGatherMaskedVal, pSrcBase, byteOffsets, vMask, C((char)1));
1047 // e.g. result of second 8x32bit integer gather for 16bit components
1048 // 256i - 0 1 2 3 4 5 6 7
1049 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
1050 //
1051 }
1052 else
1053 {
1054 vGatherResult[1] = vGatherMaskedVal;
1055 }
1056
1057 // Shuffle gathered components into place, each row is a component
1058 Shuffle16bpcGather4(info, vGatherResult, vGatherComponents, bPackedOutput);
1059
1060 }
1061 break;
1062 case 32:
1063 {
1064 // apply defaults
1065 for (uint32_t i = 0; i < 4; ++i)
1066 {
1067 vGatherComponents[i] = VIMMED1((int)info.defaults[i]);
1068 }
1069
1070 for(uint32_t i = 0; i < info.numComps; i++)
1071 {
1072 uint32_t swizzleIndex = info.swizzle[i];
1073
1074 // save mask as it is zero'd out after each gather
1075 Value *vMask = mask;
1076
1077 // Gather a SIMD of components
1078 vGatherComponents[swizzleIndex] = GATHERDD(vGatherComponents[swizzleIndex], pSrcBase, byteOffsets, vMask, C((char)1));
1079
1080 // offset base to the next component to gather
1081 pSrcBase = GEP(pSrcBase, C((char)4));
1082 }
1083 }
1084 break;
1085 default:
1086 SWR_ASSERT(0, "unsupported format");
1087 break;
1088 }
1089 }
1090
1091 void Builder::Shuffle16bpcGather4(const SWR_FORMAT_INFO &info, Value* vGatherInput[2], Value* vGatherOutput[4], bool bPackedOutput)
1092 {
1093 // cast types
1094 Type* vGatherTy = VectorType::get(IntegerType::getInt32Ty(JM()->mContext), mVWidth);
1095 Type* v32x8Ty = VectorType::get(mInt8Ty, mVWidth * 4); // vwidth is units of 32 bits
1096
1097 // input could either be float or int vector; do shuffle work in int
1098 vGatherInput[0] = BITCAST(vGatherInput[0], mSimdInt32Ty);
1099 vGatherInput[1] = BITCAST(vGatherInput[1], mSimdInt32Ty);
1100
1101 if(bPackedOutput)
1102 {
1103 Type* v128bitTy = VectorType::get(IntegerType::getIntNTy(JM()->mContext, 128), mVWidth / 4); // vwidth is units of 32 bits
1104
1105 // shuffle mask
1106 Value* vConstMask = C<char>({0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
1107 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15});
1108 Value* vShufResult = BITCAST(PSHUFB(BITCAST(vGatherInput[0], v32x8Ty), vConstMask), vGatherTy);
1109 // after pshufb: group components together in each 128bit lane
1110 // 256i - 0 1 2 3 4 5 6 7
1111 // xxxx xxxx yyyy yyyy xxxx xxxx yyyy yyyy
1112
1113 Value* vi128XY = BITCAST(PERMD(vShufResult, C<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy);
1114 // after PERMD: move and pack xy components into each 128bit lane
1115 // 256i - 0 1 2 3 4 5 6 7
1116 // xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy
1117
1118 // do the same for zw components
1119 Value* vi128ZW = nullptr;
1120 if(info.numComps > 2)
1121 {
1122 Value* vShufResult = BITCAST(PSHUFB(BITCAST(vGatherInput[1], v32x8Ty), vConstMask), vGatherTy);
1123 vi128ZW = BITCAST(PERMD(vShufResult, C<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy);
1124 }
1125
1126 for(uint32_t i = 0; i < 4; i++)
1127 {
1128 uint32_t swizzleIndex = info.swizzle[i];
1129 // todo: fixed for packed
1130 Value* vGatherMaskedVal = VIMMED1((int32_t)(info.defaults[i]));
1131 if(i >= info.numComps)
1132 {
1133 // set the default component val
1134 vGatherOutput[swizzleIndex] = vGatherMaskedVal;
1135 continue;
1136 }
1137
1138 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1139 uint32_t lane = ((i == 0) || (i == 2)) ? 0 : 1;
1140 // if x or y, use vi128XY permute result, else use vi128ZW
1141 Value* selectedPermute = (i < 2) ? vi128XY : vi128ZW;
1142
1143 // extract packed component 128 bit lanes
1144 vGatherOutput[swizzleIndex] = VEXTRACT(selectedPermute, C(lane));
1145 }
1146
1147 }
1148 else
1149 {
1150 // pshufb masks for each component
1151 Value* vConstMask[2];
1152 // x/z shuffle mask
1153 vConstMask[0] = C<char>({0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1,
1154 0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1, });
1155
1156 // y/w shuffle mask
1157 vConstMask[1] = C<char>({2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1,
1158 2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1});
1159
1160
1161 // shuffle enabled components into lower word of each 32bit lane, 0 extending to 32 bits
1162 // apply defaults
1163 for (uint32_t i = 0; i < 4; ++i)
1164 {
1165 vGatherOutput[i] = VIMMED1((int32_t)info.defaults[i]);
1166 }
1167
1168 for(uint32_t i = 0; i < info.numComps; i++)
1169 {
1170 uint32_t swizzleIndex = info.swizzle[i];
1171
1172 // select correct constMask for x/z or y/w pshufb
1173 uint32_t selectedMask = ((i == 0) || (i == 2)) ? 0 : 1;
1174 // if x or y, use vi128XY permute result, else use vi128ZW
1175 uint32_t selectedGather = (i < 2) ? 0 : 1;
1176
1177 vGatherOutput[swizzleIndex] = BITCAST(PSHUFB(BITCAST(vGatherInput[selectedGather], v32x8Ty), vConstMask[selectedMask]), vGatherTy);
1178 // after pshufb mask for x channel; z uses the same shuffle from the second gather
1179 // 256i - 0 1 2 3 4 5 6 7
1180 // xx00 xx00 xx00 xx00 xx00 xx00 xx00 xx00
1181 }
1182 }
1183 }
1184
1185 void Builder::Shuffle8bpcGather4(const SWR_FORMAT_INFO &info, Value* vGatherInput, Value* vGatherOutput[], bool bPackedOutput)
1186 {
1187 // cast types
1188 Type* vGatherTy = VectorType::get(IntegerType::getInt32Ty(JM()->mContext), mVWidth);
1189 Type* v32x8Ty = VectorType::get(mInt8Ty, mVWidth * 4 ); // vwidth is units of 32 bits
1190
1191 if(bPackedOutput)
1192 {
1193 Type* v128Ty = VectorType::get(IntegerType::getIntNTy(JM()->mContext, 128), mVWidth / 4); // vwidth is units of 32 bits
1194 // shuffle mask
1195 Value* vConstMask = C<char>({0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15,
1196 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15});
1197 Value* vShufResult = BITCAST(PSHUFB(BITCAST(vGatherInput, v32x8Ty), vConstMask), vGatherTy);
1198 // after pshufb: group components together in each 128bit lane
1199 // 256i - 0 1 2 3 4 5 6 7
1200 // xxxx yyyy zzzz wwww xxxx yyyy zzzz wwww
1201
1202 Value* vi128XY = BITCAST(PERMD(vShufResult, C<int32_t>({0, 4, 0, 0, 1, 5, 0, 0})), v128Ty);
1203 // after PERMD: move and pack xy and zw components in low 64 bits of each 128bit lane
1204 // 256i - 0 1 2 3 4 5 6 7
1205 // xxxx xxxx dcdc dcdc yyyy yyyy dcdc dcdc (dc - don't care)
1206
1207 // do the same for zw components
1208 Value* vi128ZW = nullptr;
1209 if(info.numComps > 2)
1210 {
1211 vi128ZW = BITCAST(PERMD(vShufResult, C<int32_t>({2, 6, 0, 0, 3, 7, 0, 0})), v128Ty);
1212 }
1213
1214 // sign extend all enabled components. If we have a fill vVertexElements, output to current simdvertex
1215 for(uint32_t i = 0; i < 4; i++)
1216 {
1217 uint32_t swizzleIndex = info.swizzle[i];
1218 // todo: fix for packed
1219 Value* vGatherMaskedVal = VIMMED1((int32_t)(info.defaults[i]));
1220 if(i >= info.numComps)
1221 {
1222 // set the default component val
1223 vGatherOutput[swizzleIndex] = vGatherMaskedVal;
1224 continue;
1225 }
1226
1227 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1228 uint32_t lane = ((i == 0) || (i == 2)) ? 0 : 1;
1229 // if x or y, use vi128XY permute result, else use vi128ZW
1230 Value* selectedPermute = (i < 2) ? vi128XY : vi128ZW;
1231
1232 // sign extend
1233 vGatherOutput[swizzleIndex] = VEXTRACT(selectedPermute, C(lane));
1234 }
1235 }
1236 // else zero extend
1237 else{
1238 // shuffle enabled components into lower byte of each 32bit lane, 0 extending to 32 bits
1239 // apply defaults
1240 for (uint32_t i = 0; i < 4; ++i)
1241 {
1242 vGatherOutput[i] = VIMMED1((int32_t)info.defaults[i]);
1243 }
1244
1245 for(uint32_t i = 0; i < info.numComps; i++){
1246 uint32_t swizzleIndex = info.swizzle[i];
1247
1248 // pshufb masks for each component
1249 Value* vConstMask;
1250 switch(i)
1251 {
1252 case 0:
1253 // x shuffle mask
1254 vConstMask = C<char>({0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1,
1255 0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1});
1256 break;
1257 case 1:
1258 // y shuffle mask
1259 vConstMask = C<char>({1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1,
1260 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1});
1261 break;
1262 case 2:
1263 // z shuffle mask
1264 vConstMask = C<char>({2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1,
1265 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1});
1266 break;
1267 case 3:
1268 // w shuffle mask
1269 vConstMask = C<char>({3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1,
1270 3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1});
1271 break;
1272 default:
1273 vConstMask = nullptr;
1274 break;
1275 }
1276
1277 vGatherOutput[swizzleIndex] = BITCAST(PSHUFB(BITCAST(vGatherInput, v32x8Ty), vConstMask), vGatherTy);
1278 // after pshufb for x channel
1279 // 256i - 0 1 2 3 4 5 6 7
1280 // x000 x000 x000 x000 x000 x000 x000 x000
1281 }
1282 }
1283 }
1284
1285 //////////////////////////////////////////////////////////////////////////
1286 /// @brief emulates a scatter operation.
1287 /// @param pDst - pointer to destination
1288 /// @param vSrc - vector of src data to scatter
1289 /// @param vOffsets - vector of byte offsets from pDst
1290 /// @param vMask - mask of valid lanes
1291 void Builder::SCATTERPS(Value* pDst, Value* vSrc, Value* vOffsets, Value* vMask)
1292 {
1293 Value* pStack = STACKSAVE();
1294
1295 Type* pSrcTy = vSrc->getType()->getVectorElementType();
1296
1297 // allocate tmp stack for masked off lanes
1298 Value* vTmpPtr = ALLOCA(pSrcTy);
1299
1300 Value *mask = MASK(vMask);
1301 for (uint32_t i = 0; i < mVWidth; ++i)
1302 {
1303 Value *offset = VEXTRACT(vOffsets, C(i));
1304 // byte pointer to component
1305 Value *storeAddress = GEP(pDst, offset);
1306 storeAddress = BITCAST(storeAddress, PointerType::get(pSrcTy, 0));
1307 Value *selMask = VEXTRACT(mask, C(i));
1308 Value *srcElem = VEXTRACT(vSrc, C(i));
1309 // switch in a safe address to load if we're trying to access a vertex
1310 Value *validAddress = SELECT(selMask, storeAddress, vTmpPtr);
1311 STORE(srcElem, validAddress);
1312 }
1313
1314 STACKRESTORE(pStack);
1315 }
1316
1317 Value* Builder::VABSPS(Value* a)
1318 {
1319 Value* asInt = BITCAST(a, mSimdInt32Ty);
1320 Value* result = BITCAST(AND(asInt, VIMMED1(0x7fffffff)), mSimdFP32Ty);
1321 return result;
1322 }
1323
1324 Value *Builder::ICLAMP(Value* src, Value* low, Value* high)
1325 {
1326 Value *lowCmp = ICMP_SLT(src, low);
1327 Value *ret = SELECT(lowCmp, low, src);
1328
1329 Value *highCmp = ICMP_SGT(ret, high);
1330 ret = SELECT(highCmp, high, ret);
1331
1332 return ret;
1333 }
1334
1335 Value *Builder::FCLAMP(Value* src, Value* low, Value* high)
1336 {
1337 Value *lowCmp = FCMP_OLT(src, low);
1338 Value *ret = SELECT(lowCmp, low, src);
1339
1340 Value *highCmp = FCMP_OGT(ret, high);
1341 ret = SELECT(highCmp, high, ret);
1342
1343 return ret;
1344 }
1345
1346 Value *Builder::FCLAMP(Value* src, float low, float high)
1347 {
1348 Value* result = VMAXPS(src, VIMMED1(low));
1349 result = VMINPS(result, VIMMED1(high));
1350
1351 return result;
1352 }
1353
1354 //////////////////////////////////////////////////////////////////////////
1355 /// @brief save/restore stack, providing ability to push/pop the stack and
1356 /// reduce overall stack requirements for temporary stack use
1357 Value* Builder::STACKSAVE()
1358 {
1359 Function* pfnStackSave = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::stacksave);
1360 #if HAVE_LLVM == 0x306
1361 return CALL(pfnStackSave);
1362 #else
1363 return CALLA(pfnStackSave);
1364 #endif
1365 }
1366
1367 void Builder::STACKRESTORE(Value* pSaved)
1368 {
1369 Function* pfnStackRestore = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::stackrestore);
1370 CALL(pfnStackRestore, std::initializer_list<Value*>{pSaved});
1371 }
1372
1373 Value *Builder::FMADDPS(Value* a, Value* b, Value* c)
1374 {
1375 Value* vOut;
1376 // use FMADs if available
1377 if(JM()->mArch.AVX2())
1378 {
1379 vOut = VFMADDPS(a, b, c);
1380 }
1381 else
1382 {
1383 vOut = FADD(FMUL(a, b), c);
1384 }
1385 return vOut;
1386 }
1387
1388 Value* Builder::POPCNT(Value* a)
1389 {
1390 Function* pCtPop = Intrinsic::getDeclaration(JM()->mpCurrentModule, Intrinsic::ctpop, { a->getType() });
1391 return CALL(pCtPop, std::initializer_list<Value*>{a});
1392 }
1393
1394 //////////////////////////////////////////////////////////////////////////
1395 /// @brief C functions called by LLVM IR
1396 //////////////////////////////////////////////////////////////////////////
1397
1398 //////////////////////////////////////////////////////////////////////////
1399 /// @brief called in JIT code, inserted by PRINT
1400 /// output to both stdout and visual studio debug console
1401 void __cdecl CallPrint(const char* fmt, ...)
1402 {
1403 va_list args;
1404 va_start(args, fmt);
1405 vprintf(fmt, args);
1406
1407 #if defined( _WIN32 )
1408 char strBuf[1024];
1409 vsnprintf_s(strBuf, _TRUNCATE, fmt, args);
1410 OutputDebugString(strBuf);
1411 #endif
1412
1413 va_end(args);
1414 }
1415
1416 Value *Builder::VEXTRACTI128(Value* a, Constant* imm8)
1417 {
1418 #if HAVE_LLVM == 0x306
1419 Function *func =
1420 Intrinsic::getDeclaration(JM()->mpCurrentModule,
1421 Intrinsic::x86_avx_vextractf128_si_256);
1422 return CALL(func, {a, imm8});
1423 #else
1424 bool flag = !imm8->isZeroValue();
1425 SmallVector<Constant*,8> idx;
1426 for (unsigned i = 0; i < mVWidth / 2; i++) {
1427 idx.push_back(C(flag ? i + mVWidth / 2 : i));
1428 }
1429 return VSHUFFLE(a, VUNDEF_I(), ConstantVector::get(idx));
1430 #endif
1431 }
1432
1433 Value *Builder::VINSERTI128(Value* a, Value* b, Constant* imm8)
1434 {
1435 #if HAVE_LLVM == 0x306
1436 Function *func =
1437 Intrinsic::getDeclaration(JM()->mpCurrentModule,
1438 Intrinsic::x86_avx_vinsertf128_si_256);
1439 return CALL(func, {a, b, imm8});
1440 #else
1441 bool flag = !imm8->isZeroValue();
1442 SmallVector<Constant*,8> idx;
1443 for (unsigned i = 0; i < mVWidth; i++) {
1444 idx.push_back(C(i));
1445 }
1446 Value *inter = VSHUFFLE(b, VUNDEF_I(), ConstantVector::get(idx));
1447
1448 SmallVector<Constant*,8> idx2;
1449 for (unsigned i = 0; i < mVWidth / 2; i++) {
1450 idx2.push_back(C(flag ? i : i + mVWidth));
1451 }
1452 for (unsigned i = mVWidth / 2; i < mVWidth; i++) {
1453 idx2.push_back(C(flag ? i + mVWidth / 2 : i));
1454 }
1455 return VSHUFFLE(a, inter, ConstantVector::get(idx2));
1456 #endif
1457 }
1458
1459 // rdtsc buckets macros
1460 void Builder::RDTSC_START(Value* pBucketMgr, Value* pId)
1461 {
1462 std::vector<Type*> args{
1463 PointerType::get(mInt32Ty, 0), // pBucketMgr
1464 mInt32Ty // id
1465 };
1466
1467 FunctionType* pFuncTy = FunctionType::get(Type::getVoidTy(JM()->mContext), args, false);
1468 Function* pFunc = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("BucketManager_StartBucket", pFuncTy));
1469 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StartBucket") == nullptr)
1470 {
1471 sys::DynamicLibrary::AddSymbol("BucketManager_StartBucket", (void*)&BucketManager_StartBucket);
1472 }
1473
1474 CALL(pFunc, { pBucketMgr, pId });
1475 }
1476
1477 void Builder::RDTSC_STOP(Value* pBucketMgr, Value* pId)
1478 {
1479 std::vector<Type*> args{
1480 PointerType::get(mInt32Ty, 0), // pBucketMgr
1481 mInt32Ty // id
1482 };
1483
1484 FunctionType* pFuncTy = FunctionType::get(Type::getVoidTy(JM()->mContext), args, false);
1485 Function* pFunc = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("BucketManager_StopBucket", pFuncTy));
1486 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StopBucket") == nullptr)
1487 {
1488 sys::DynamicLibrary::AddSymbol("BucketManager_StopBucket", (void*)&BucketManager_StopBucket);
1489 }
1490
1491 CALL(pFunc, { pBucketMgr, pId });
1492 }
1493