1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
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:
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
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
23 * @file builder_misc.cpp
25 * @brief Implementation for miscellaneous builder functions
29 ******************************************************************************/
31 #include "common/rdtsc_buckets.h"
37 void __cdecl
CallPrint(const char* fmt
, ...);
39 //////////////////////////////////////////////////////////////////////////
40 /// @brief Convert an IEEE 754 32-bit single precision float to an
41 /// 16 bit float with 5 exponent bits and a variable
42 /// number of mantissa bits.
43 /// @param val - 32-bit float
44 /// @todo Maybe move this outside of this file into a header?
45 static uint16_t ConvertFloat32ToFloat16(float val
)
47 uint32_t sign
, exp
, mant
;
50 // Extract the sign, exponent, and mantissa
51 uint32_t uf
= *(uint32_t*)&val
;
52 sign
= (uf
& 0x80000000) >> 31;
53 exp
= (uf
& 0x7F800000) >> 23;
54 mant
= uf
& 0x007FFFFF;
56 // Check for out of range
61 sign
= 1; // set the sign bit for NANs
63 else if (std::isinf(val
))
68 else if (exp
> (0x70 + 0x1E)) // Too big to represent -> max representable value
73 else if ((exp
<= 0x70) && (exp
>= 0x66)) // It's a denorm
76 for (; exp
<= 0x70; mant
>>= 1, exp
++)
81 else if (exp
< 0x66) // Too small to represent -> Zero
88 // Saves bits that will be shifted off for rounding
89 roundBits
= mant
& 0x1FFFu
;
90 // convert exponent and mantissa to 16 bit format
94 // Essentially RTZ, but round up if off by only 1 lsb
95 if (roundBits
== 0x1FFFu
)
99 if ((mant
& 0xC00u
) != 0)
101 // make sure only the needed bits are used
106 uint32_t tmpVal
= (sign
<< 15) | (exp
<< 10) | mant
;
107 return (uint16_t)tmpVal
;
110 //////////////////////////////////////////////////////////////////////////
111 /// @brief Convert an IEEE 754 16-bit float to an 32-bit single precision
113 /// @param val - 16-bit float
114 /// @todo Maybe move this outside of this file into a header?
115 static float ConvertFloat16ToFloat32(uint32_t val
)
118 if ((val
& 0x7fff) == 0)
120 result
= ((uint32_t)(val
& 0x8000)) << 16;
122 else if ((val
& 0x7c00) == 0x7c00)
124 result
= ((val
& 0x3ff) == 0) ? 0x7f800000 : 0x7fc00000;
125 result
|= ((uint32_t)val
& 0x8000) << 16;
129 uint32_t sign
= (val
& 0x8000) << 16;
130 uint32_t mant
= (val
& 0x3ff) << 13;
131 uint32_t exp
= (val
>> 10) & 0x1f;
132 if ((exp
== 0) && (mant
!= 0)) // Adjust exponent and mantissa for denormals
135 while (mant
< (0x400 << 13))
140 mant
&= (0x3ff << 13);
142 exp
= ((exp
- 15 + 127) & 0xff) << 23;
143 result
= sign
| exp
| mant
;
146 return *(float*)&result
;
149 Constant
*Builder::C(bool i
)
151 return ConstantInt::get(IRB()->getInt1Ty(), (i
? 1 : 0));
154 Constant
*Builder::C(char i
)
156 return ConstantInt::get(IRB()->getInt8Ty(), i
);
159 Constant
*Builder::C(uint8_t i
)
161 return ConstantInt::get(IRB()->getInt8Ty(), i
);
164 Constant
*Builder::C(int i
)
166 return ConstantInt::get(IRB()->getInt32Ty(), i
);
169 Constant
*Builder::C(int64_t i
)
171 return ConstantInt::get(IRB()->getInt64Ty(), i
);
174 Constant
*Builder::C(uint16_t i
)
176 return ConstantInt::get(mInt16Ty
,i
);
179 Constant
*Builder::C(uint32_t i
)
181 return ConstantInt::get(IRB()->getInt32Ty(), i
);
184 Constant
*Builder::C(float i
)
186 return ConstantFP::get(IRB()->getFloatTy(), i
);
189 Constant
*Builder::PRED(bool pred
)
191 return ConstantInt::get(IRB()->getInt1Ty(), (pred
? 1 : 0));
194 Value
*Builder::VIMMED1(int i
)
196 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
199 Value
*Builder::VIMMED1(uint32_t i
)
201 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
204 Value
*Builder::VIMMED1(float i
)
206 return ConstantVector::getSplat(mVWidth
, cast
<ConstantFP
>(C(i
)));
209 Value
*Builder::VIMMED1(bool i
)
211 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
214 #if USE_SIMD16_BUILDER
215 Value
*Builder::VIMMED2_1(int i
)
217 return ConstantVector::getSplat(mVWidth2
, cast
<ConstantInt
>(C(i
)));
220 Value
*Builder::VIMMED2_1(uint32_t i
)
222 return ConstantVector::getSplat(mVWidth2
, cast
<ConstantInt
>(C(i
)));
225 Value
*Builder::VIMMED2_1(float i
)
227 return ConstantVector::getSplat(mVWidth2
, cast
<ConstantFP
>(C(i
)));
230 Value
*Builder::VIMMED2_1(bool i
)
232 return ConstantVector::getSplat(mVWidth2
, cast
<ConstantInt
>(C(i
)));
236 Value
*Builder::VUNDEF_IPTR()
238 return UndefValue::get(VectorType::get(mInt32PtrTy
,mVWidth
));
241 Value
*Builder::VUNDEF_I()
243 return UndefValue::get(VectorType::get(mInt32Ty
, mVWidth
));
246 Value
*Builder::VUNDEF(Type
*ty
, uint32_t size
)
248 return UndefValue::get(VectorType::get(ty
, size
));
251 Value
*Builder::VUNDEF_F()
253 return UndefValue::get(VectorType::get(mFP32Ty
, mVWidth
));
256 #if USE_SIMD16_BUILDER
257 Value
*Builder::VUNDEF2_F()
259 return UndefValue::get(VectorType::get(mFP32Ty
, mVWidth2
));
262 Value
*Builder::VUNDEF2_I()
264 return UndefValue::get(VectorType::get(mInt32Ty
, mVWidth2
));
268 Value
*Builder::VUNDEF(Type
* t
)
270 return UndefValue::get(VectorType::get(t
, mVWidth
));
273 Value
*Builder::VBROADCAST(Value
*src
)
275 // check if src is already a vector
276 if (src
->getType()->isVectorTy())
281 return VECTOR_SPLAT(mVWidth
, src
);
284 #if USE_SIMD16_BUILDER
285 Value
*Builder::VBROADCAST2(Value
*src
)
287 // check if src is already a vector
288 if (src
->getType()->isVectorTy())
293 return VECTOR_SPLAT(mVWidth2
, src
);
297 uint32_t Builder::IMMED(Value
* v
)
299 SWR_ASSERT(isa
<ConstantInt
>(v
));
300 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
301 return pValConst
->getZExtValue();
304 int32_t Builder::S_IMMED(Value
* v
)
306 SWR_ASSERT(isa
<ConstantInt
>(v
));
307 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
308 return pValConst
->getSExtValue();
311 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<Value
*> &indexList
)
313 std::vector
<Value
*> indices
;
314 for (auto i
: indexList
)
315 indices
.push_back(i
);
316 return GEPA(ptr
, indices
);
319 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<uint32_t> &indexList
)
321 std::vector
<Value
*> indices
;
322 for (auto i
: indexList
)
323 indices
.push_back(C(i
));
324 return GEPA(ptr
, indices
);
327 Value
*Builder::IN_BOUNDS_GEP(Value
* ptr
, const std::initializer_list
<Value
*> &indexList
)
329 std::vector
<Value
*> indices
;
330 for (auto i
: indexList
)
331 indices
.push_back(i
);
332 return IN_BOUNDS_GEP(ptr
, indices
);
335 Value
*Builder::IN_BOUNDS_GEP(Value
* ptr
, const std::initializer_list
<uint32_t> &indexList
)
337 std::vector
<Value
*> indices
;
338 for (auto i
: indexList
)
339 indices
.push_back(C(i
));
340 return IN_BOUNDS_GEP(ptr
, indices
);
343 LoadInst
*Builder::LOAD(Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
, const llvm::Twine
& name
)
345 std::vector
<Value
*> valIndices
;
346 for (auto i
: indices
)
347 valIndices
.push_back(C(i
));
348 return LOAD(GEPA(basePtr
, valIndices
), name
);
351 LoadInst
*Builder::LOADV(Value
*basePtr
, const std::initializer_list
<Value
*> &indices
, const llvm::Twine
& name
)
353 std::vector
<Value
*> valIndices
;
354 for (auto i
: indices
)
355 valIndices
.push_back(i
);
356 return LOAD(GEPA(basePtr
, valIndices
), name
);
359 StoreInst
*Builder::STORE(Value
*val
, Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
)
361 std::vector
<Value
*> valIndices
;
362 for (auto i
: indices
)
363 valIndices
.push_back(C(i
));
364 return STORE(val
, GEPA(basePtr
, valIndices
));
367 StoreInst
*Builder::STOREV(Value
*val
, Value
*basePtr
, const std::initializer_list
<Value
*> &indices
)
369 std::vector
<Value
*> valIndices
;
370 for (auto i
: indices
)
371 valIndices
.push_back(i
);
372 return STORE(val
, GEPA(basePtr
, valIndices
));
375 CallInst
*Builder::CALL(Value
*Callee
, const std::initializer_list
<Value
*> &argsList
)
377 std::vector
<Value
*> args
;
378 for (auto arg
: argsList
)
380 return CALLA(Callee
, args
);
383 CallInst
*Builder::CALL(Value
*Callee
, Value
* arg
)
385 std::vector
<Value
*> args
;
387 return CALLA(Callee
, args
);
390 CallInst
*Builder::CALL2(Value
*Callee
, Value
* arg1
, Value
* arg2
)
392 std::vector
<Value
*> args
;
393 args
.push_back(arg1
);
394 args
.push_back(arg2
);
395 return CALLA(Callee
, args
);
398 CallInst
*Builder::CALL3(Value
*Callee
, Value
* arg1
, Value
* arg2
, Value
* arg3
)
400 std::vector
<Value
*> args
;
401 args
.push_back(arg1
);
402 args
.push_back(arg2
);
403 args
.push_back(arg3
);
404 return CALLA(Callee
, args
);
407 //////////////////////////////////////////////////////////////////////////
408 Value
*Builder::DEBUGTRAP()
410 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::debugtrap
);
414 Value
*Builder::VRCP(Value
*va
)
416 return FDIV(VIMMED1(1.0f
), va
); // 1 / a
419 Value
*Builder::VPLANEPS(Value
* vA
, Value
* vB
, Value
* vC
, Value
* &vX
, Value
* &vY
)
421 Value
* vOut
= FMADDPS(vA
, vX
, vC
);
422 vOut
= FMADDPS(vB
, vY
, vOut
);
426 //////////////////////////////////////////////////////////////////////////
427 /// @brief Generate an i32 masked load operation in LLVM IR. If not
428 /// supported on the underlying platform, emulate it with float masked load
429 /// @param src - base address pointer for the load
430 /// @param vMask - SIMD wide mask that controls whether to access memory load 0
431 Value
*Builder::MASKLOADD(Value
* src
,Value
* mask
)
434 // use avx2 gather instruction is available
435 if(JM()->mArch
.AVX2())
437 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_avx2_maskload_d_256
);
438 vResult
= CALL(func
,{src
,mask
});
442 // maskload intrinsic expects integer mask operand in llvm >= 3.8
443 #if (LLVM_VERSION_MAJOR > 3) || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 8)
444 mask
= BITCAST(mask
,VectorType::get(mInt32Ty
,mVWidth
));
446 mask
= BITCAST(mask
,VectorType::get(mFP32Ty
,mVWidth
));
448 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
,Intrinsic::x86_avx_maskload_ps_256
);
449 vResult
= BITCAST(CALL(func
,{src
,mask
}), VectorType::get(mInt32Ty
,mVWidth
));
454 //////////////////////////////////////////////////////////////////////////
455 /// @brief insert a JIT call to CallPrint
456 /// - outputs formatted string to both stdout and VS output window
457 /// - DEBUG builds only
459 /// PRINT("index %d = 0x%p\n",{C(lane), pIndex});
460 /// where C(lane) creates a constant value to print, and pIndex is the Value*
461 /// result from a GEP, printing out the pointer to memory
462 /// @param printStr - constant string to print, which includes format specifiers
463 /// @param printArgs - initializer list of Value*'s to print to std out
464 CallInst
*Builder::PRINT(const std::string
&printStr
,const std::initializer_list
<Value
*> &printArgs
)
466 // push the arguments to CallPrint into a vector
467 std::vector
<Value
*> printCallArgs
;
468 // save room for the format string. we still need to modify it for vectors
469 printCallArgs
.resize(1);
471 // search through the format string for special processing
473 std::string
tempStr(printStr
);
474 pos
= tempStr
.find('%', pos
);
475 auto v
= printArgs
.begin();
477 while ((pos
!= std::string::npos
) && (v
!= printArgs
.end()))
480 Type
* pType
= pArg
->getType();
482 if (pType
->isVectorTy())
484 Type
* pContainedType
= pType
->getContainedType(0);
486 if (toupper(tempStr
[pos
+ 1]) == 'X')
489 tempStr
[pos
+ 1] = 'x';
490 tempStr
.insert(pos
+ 2, "%08X ");
493 printCallArgs
.push_back(VEXTRACT(pArg
, C(0)));
495 std::string vectorFormatStr
;
496 for (uint32_t i
= 1; i
< pType
->getVectorNumElements(); ++i
)
498 vectorFormatStr
+= "0x%08X ";
499 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
502 tempStr
.insert(pos
, vectorFormatStr
);
503 pos
+= vectorFormatStr
.size();
505 else if ((tempStr
[pos
+ 1] == 'f') && (pContainedType
->isFloatTy()))
508 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
510 tempStr
.insert(pos
, std::string("%f "));
512 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
514 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
516 else if ((tempStr
[pos
+ 1] == 'd') && (pContainedType
->isIntegerTy()))
519 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
521 tempStr
.insert(pos
, std::string("%d "));
523 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
525 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
530 if (toupper(tempStr
[pos
+ 1]) == 'X')
533 tempStr
.insert(pos
+ 1, "x%08");
534 printCallArgs
.push_back(pArg
);
537 // for %f we need to cast float Values to doubles so that they print out correctly
538 else if ((tempStr
[pos
+ 1] == 'f') && (pType
->isFloatTy()))
540 printCallArgs
.push_back(FP_EXT(pArg
, Type::getDoubleTy(JM()->mContext
)));
545 printCallArgs
.push_back(pArg
);
549 // advance to the next arguement
551 pos
= tempStr
.find('%', ++pos
);
554 // create global variable constant string
555 Constant
*constString
= ConstantDataArray::getString(JM()->mContext
,tempStr
,true);
556 GlobalVariable
*gvPtr
= new GlobalVariable(constString
->getType(),true,GlobalValue::InternalLinkage
,constString
,"printStr");
557 JM()->mpCurrentModule
->getGlobalList().push_back(gvPtr
);
559 // get a pointer to the first character in the constant string array
560 std::vector
<Constant
*> geplist
{C(0),C(0)};
561 Constant
*strGEP
= ConstantExpr::getGetElementPtr(nullptr, gvPtr
,geplist
,false);
563 // insert the pointer to the format string in the argument vector
564 printCallArgs
[0] = strGEP
;
566 // get pointer to CallPrint function and insert decl into the module if needed
567 std::vector
<Type
*> args
;
568 args
.push_back(PointerType::get(mInt8Ty
,0));
569 FunctionType
* callPrintTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
),args
,true);
570 Function
*callPrintFn
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("CallPrint", callPrintTy
));
572 // if we haven't yet added the symbol to the symbol table
573 if((sys::DynamicLibrary::SearchForAddressOfSymbol("CallPrint")) == nullptr)
575 sys::DynamicLibrary::AddSymbol("CallPrint", (void *)&CallPrint
);
578 // insert a call to CallPrint
579 return CALLA(callPrintFn
,printCallArgs
);
582 //////////////////////////////////////////////////////////////////////////
583 /// @brief Wrapper around PRINT with initializer list.
584 CallInst
* Builder::PRINT(const std::string
&printStr
)
586 return PRINT(printStr
, {});
589 //////////////////////////////////////////////////////////////////////////
590 /// @brief Generate a masked gather operation in LLVM IR. If not
591 /// supported on the underlying platform, emulate it with loads
592 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
593 /// @param pBase - Int8* base VB address pointer value
594 /// @param vIndices - SIMD wide value of VB byte offsets
595 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
596 /// @param scale - value to scale indices by
597 Value
*Builder::GATHERPS(Value
*vSrc
, Value
*pBase
, Value
*vIndices
, Value
*vMask
, uint8_t scale
)
601 // use avx2 gather instruction if available
602 if(JM()->mArch
.AVX2())
604 // force mask to <N x float>, required by vgather
605 Value
*mask
= BITCAST(vMask
, mSimdFP32Ty
);
607 vGather
= VGATHERPS(vSrc
, pBase
, vIndices
, mask
, C(scale
));
611 Value
* pStack
= STACKSAVE();
613 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
614 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
615 STORE(vSrc
, vSrcPtr
);
617 vGather
= VUNDEF_F();
618 Value
*vScaleVec
= VIMMED1((uint32_t)scale
);
619 Value
*vOffsets
= MUL(vIndices
,vScaleVec
);
620 Value
*mask
= MASK(vMask
);
621 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
623 // single component byte index
624 Value
*offset
= VEXTRACT(vOffsets
,C(i
));
625 // byte pointer to component
626 Value
*loadAddress
= GEP(pBase
,offset
);
627 loadAddress
= BITCAST(loadAddress
,PointerType::get(mFP32Ty
,0));
628 // pointer to the value to load if we're masking off a component
629 Value
*maskLoadAddress
= GEP(vSrcPtr
,{C(0), C(i
)});
630 Value
*selMask
= VEXTRACT(mask
,C(i
));
631 // switch in a safe address to load if we're trying to access a vertex
632 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
633 Value
*val
= LOAD(validAddress
);
634 vGather
= VINSERT(vGather
,val
,C(i
));
636 STACKRESTORE(pStack
);
642 #if USE_SIMD16_BUILDER
643 Value
*Builder::GATHERPS2(Value
*vSrc
, Value
*pBase
, Value
*vIndices
, Value
*vMask
, uint8_t scale
)
645 Value
*vGather
= VUNDEF2_F();
647 // use avx512 gather instruction if available
648 if (JM()->mArch
.AVX512F())
650 // force mask to <N-bit Integer>, required by vgather2
651 Value
*mask
= BITCAST(MASK2(vMask
), mInt16Ty
);
653 vGather
= VGATHERPS2(vSrc
, pBase
, vIndices
, mask
, C((uint32_t)scale
));
657 Value
*src0
= EXTRACT2_F(vSrc
, 0);
658 Value
*src1
= EXTRACT2_F(vSrc
, 1);
660 Value
*indices0
= EXTRACT2_I(vIndices
, 0);
661 Value
*indices1
= EXTRACT2_I(vIndices
, 1);
663 Value
*mask0
= EXTRACT2_I(vMask
, 0);
664 Value
*mask1
= EXTRACT2_I(vMask
, 1);
666 Value
*gather0
= GATHERPS(src0
, pBase
, indices0
, mask0
, scale
);
667 Value
*gather1
= GATHERPS(src1
, pBase
, indices1
, mask1
, scale
);
669 vGather
= INSERT2_F(vGather
, gather0
, 0);
670 vGather
= INSERT2_F(vGather
, gather1
, 1);
677 //////////////////////////////////////////////////////////////////////////
678 /// @brief Generate a masked gather operation in LLVM IR. If not
679 /// supported on the underlying platform, emulate it with loads
680 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
681 /// @param pBase - Int8* base VB address pointer value
682 /// @param vIndices - SIMD wide value of VB byte offsets
683 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
684 /// @param scale - value to scale indices by
685 Value
*Builder::GATHERDD(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, uint8_t scale
)
689 // use avx2 gather instruction if available
690 if(JM()->mArch
.AVX2())
692 vGather
= VGATHERDD(vSrc
, pBase
, vIndices
, vMask
, C(scale
));
696 Value
* pStack
= STACKSAVE();
698 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
699 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
700 STORE(vSrc
, vSrcPtr
);
702 vGather
= VUNDEF_I();
703 Value
*vScaleVec
= VIMMED1((uint32_t)scale
);
704 Value
*vOffsets
= MUL(vIndices
, vScaleVec
);
705 Value
*mask
= MASK(vMask
);
706 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
708 // single component byte index
709 Value
*offset
= VEXTRACT(vOffsets
, C(i
));
710 // byte pointer to component
711 Value
*loadAddress
= GEP(pBase
, offset
);
712 loadAddress
= BITCAST(loadAddress
, PointerType::get(mInt32Ty
, 0));
713 // pointer to the value to load if we're masking off a component
714 Value
*maskLoadAddress
= GEP(vSrcPtr
, {C(0), C(i
)});
715 Value
*selMask
= VEXTRACT(mask
, C(i
));
716 // switch in a safe address to load if we're trying to access a vertex
717 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
718 Value
*val
= LOAD(validAddress
, C(0));
719 vGather
= VINSERT(vGather
, val
, C(i
));
722 STACKRESTORE(pStack
);
727 //////////////////////////////////////////////////////////////////////////
728 /// @brief Generate a masked gather operation in LLVM IR. If not
729 /// supported on the underlying platform, emulate it with loads
730 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
731 /// @param pBase - Int8* base VB address pointer value
732 /// @param vIndices - SIMD wide value of VB byte offsets
733 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
734 /// @param scale - value to scale indices by
735 Value
*Builder::GATHERPD(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, uint8_t scale
)
739 // use avx2 gather instruction if available
740 if(JM()->mArch
.AVX2())
742 vGather
= VGATHERPD(vSrc
, pBase
, vIndices
, vMask
, C(scale
));
746 Value
* pStack
= STACKSAVE();
748 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
749 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
750 STORE(vSrc
, vSrcPtr
);
752 vGather
= UndefValue::get(VectorType::get(mDoubleTy
, 4));
753 Value
*vScaleVec
= VECTOR_SPLAT(4, C((uint32_t)scale
));
754 Value
*vOffsets
= MUL(vIndices
,vScaleVec
);
755 Value
*mask
= MASK(vMask
);
756 for(uint32_t i
= 0; i
< mVWidth
/2; ++i
)
758 // single component byte index
759 Value
*offset
= VEXTRACT(vOffsets
,C(i
));
760 // byte pointer to component
761 Value
*loadAddress
= GEP(pBase
,offset
);
762 loadAddress
= BITCAST(loadAddress
,PointerType::get(mDoubleTy
,0));
763 // pointer to the value to load if we're masking off a component
764 Value
*maskLoadAddress
= GEP(vSrcPtr
,{C(0), C(i
)});
765 Value
*selMask
= VEXTRACT(mask
,C(i
));
766 // switch in a safe address to load if we're trying to access a vertex
767 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
768 Value
*val
= LOAD(validAddress
);
769 vGather
= VINSERT(vGather
,val
,C(i
));
771 STACKRESTORE(pStack
);
776 #if USE_SIMD16_BUILDER
777 //////////////////////////////////////////////////////////////////////////
779 Value
*Builder::EXTRACT2_F(Value
*a2
, uint32_t imm
)
781 const uint32_t i0
= (imm
> 0) ? mVWidth
: 0;
783 Value
*result
= VUNDEF_F();
785 for (uint32_t i
= 0; i
< mVWidth
; i
+= 1)
788 if (!a2
->getType()->getScalarType()->isFloatTy())
790 a2
= BITCAST(a2
, mSimd2FP32Ty
);
794 Value
*temp
= VEXTRACT(a2
, C(i0
+ i
));
796 result
= VINSERT(result
, temp
, C(i
));
802 Value
*Builder::EXTRACT2_I(Value
*a2
, uint32_t imm
)
804 return BITCAST(EXTRACT2_F(a2
, imm
), mSimdInt32Ty
);
807 //////////////////////////////////////////////////////////////////////////
809 Value
*Builder::INSERT2_F(Value
*a2
, Value
*b
, uint32_t imm
)
811 const uint32_t i0
= (imm
> 0) ? mVWidth
: 0;
813 Value
*result
= BITCAST(a2
, mSimd2FP32Ty
);
815 for (uint32_t i
= 0; i
< mVWidth
; i
+= 1)
818 if (!b
->getType()->getScalarType()->isFloatTy())
820 b
= BITCAST(b
, mSimdFP32Ty
);
824 Value
*temp
= VEXTRACT(b
, C(i
));
826 result
= VINSERT(result
, temp
, C(i0
+ i
));
832 Value
*Builder::INSERT2_I(Value
*a2
, Value
*b
, uint32_t imm
)
834 return BITCAST(INSERT2_F(a2
, b
, imm
), mSimd2Int32Ty
);
838 //////////////////////////////////////////////////////////////////////////
839 /// @brief convert x86 <N x float> mask to llvm <N x i1> mask
840 Value
*Builder::MASK(Value
*vmask
)
842 Value
*src
= BITCAST(vmask
, mSimdInt32Ty
);
843 return ICMP_SLT(src
, VIMMED1(0));
846 #if USE_SIMD16_BUILDER
847 Value
*Builder::MASK2(Value
*vmask
)
849 Value
*src
= BITCAST(vmask
, mSimd2Int32Ty
);
850 return ICMP_SLT(src
, VIMMED2_1(0));
854 //////////////////////////////////////////////////////////////////////////
855 /// @brief convert llvm <N x i1> mask to x86 <N x i32> mask
856 Value
*Builder::VMASK(Value
*mask
)
858 return S_EXT(mask
, mSimdInt32Ty
);
861 #if USE_SIMD16_BUILDER
862 Value
*Builder::VMASK2(Value
*mask
)
864 return S_EXT(mask
, mSimd2Int32Ty
);
868 //////////////////////////////////////////////////////////////////////////
869 /// @brief Generate a VPSHUFB operation in LLVM IR. If not
870 /// supported on the underlying platform, emulate it
871 /// @param a - 256bit SIMD(32x8bit) of 8bit integer values
872 /// @param b - 256bit SIMD(32x8bit) of 8bit integer mask values
873 /// Byte masks in lower 128 lane of b selects 8 bit values from lower
874 /// 128bits of a, and vice versa for the upper lanes. If the mask
875 /// value is negative, '0' is inserted.
876 Value
*Builder::PSHUFB(Value
* a
, Value
* b
)
879 // use avx2 pshufb instruction if available
880 if(JM()->mArch
.AVX2())
886 Constant
* cB
= dyn_cast
<Constant
>(b
);
887 // number of 8 bit elements in b
888 uint32_t numElms
= cast
<VectorType
>(cB
->getType())->getNumElements();
890 Value
* vShuf
= UndefValue::get(VectorType::get(mInt8Ty
, numElms
));
892 // insert an 8 bit value from the high and low lanes of a per loop iteration
894 for(uint32_t i
= 0; i
< numElms
; i
++)
896 ConstantInt
* cLow128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
));
897 ConstantInt
* cHigh128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
+ numElms
));
899 // extract values from constant mask
900 char valLow128bLane
= (char)(cLow128b
->getSExtValue());
901 char valHigh128bLane
= (char)(cHigh128b
->getSExtValue());
903 Value
* insertValLow128b
;
904 Value
* insertValHigh128b
;
906 // if the mask value is negative, insert a '0' in the respective output position
907 // otherwise, lookup the value at mask position (bits 3..0 of the respective mask byte) in a and insert in output vector
908 insertValLow128b
= (valLow128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valLow128bLane
& 0xF)));
909 insertValHigh128b
= (valHigh128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valHigh128bLane
& 0xF) + numElms
));
911 vShuf
= VINSERT(vShuf
, insertValLow128b
, i
);
912 vShuf
= VINSERT(vShuf
, insertValHigh128b
, (i
+ numElms
));
919 //////////////////////////////////////////////////////////////////////////
920 /// @brief Generate a VPSHUFB operation (sign extend 8 8bit values to 32
921 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
922 /// @param a - 128bit SIMD lane(16x8bit) of 8bit integer values. Only
923 /// lower 8 values are used.
924 Value
*Builder::PMOVSXBD(Value
* a
)
926 // VPMOVSXBD output type
927 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
928 // Extract 8 values from 128bit lane and sign extend
929 return S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
932 //////////////////////////////////////////////////////////////////////////
933 /// @brief Generate a VPSHUFB operation (sign extend 8 16bit values to 32
934 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
935 /// @param a - 128bit SIMD lane(8x16bit) of 16bit integer values.
936 Value
*Builder::PMOVSXWD(Value
* a
)
938 // VPMOVSXWD output type
939 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
940 // Extract 8 values from 128bit lane and sign extend
941 return S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
944 //////////////////////////////////////////////////////////////////////////
945 /// @brief Generate a VPERMD operation (shuffle 32 bit integer values
946 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
947 /// platform, emulate it
948 /// @param a - 256bit SIMD lane(8x32bit) of integer values.
949 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
950 Value
*Builder::PERMD(Value
* a
, Value
* idx
)
953 // use avx2 permute instruction if available
954 if(JM()->mArch
.AVX2())
956 res
= VPERMD(a
, idx
);
960 if (isa
<Constant
>(idx
))
962 res
= VSHUFFLE(a
, a
, idx
);
967 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
969 Value
* pIndex
= VEXTRACT(idx
, C(l
));
970 Value
* pVal
= VEXTRACT(a
, pIndex
);
971 res
= VINSERT(res
, pVal
, C(l
));
978 //////////////////////////////////////////////////////////////////////////
979 /// @brief Generate a VPERMPS operation (shuffle 32 bit float values
980 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
981 /// platform, emulate it
982 /// @param a - 256bit SIMD lane(8x32bit) of float values.
983 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
984 Value
*Builder::PERMPS(Value
* a
, Value
* idx
)
987 // use avx2 permute instruction if available
988 if (JM()->mArch
.AVX2())
990 // llvm 3.6.0 swapped the order of the args to vpermd
991 res
= VPERMPS(idx
, a
);
995 if (isa
<Constant
>(idx
))
997 res
= VSHUFFLE(a
, a
, idx
);
1002 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
1004 Value
* pIndex
= VEXTRACT(idx
, C(l
));
1005 Value
* pVal
= VEXTRACT(a
, pIndex
);
1006 res
= VINSERT(res
, pVal
, C(l
));
1014 //////////////////////////////////////////////////////////////////////////
1015 /// @brief Generate a VCVTPH2PS operation (float16->float32 conversion)
1016 /// in LLVM IR. If not supported on the underlying platform, emulate it
1017 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
1018 Value
*Builder::CVTPH2PS(Value
* a
)
1020 if (JM()->mArch
.F16C())
1022 return VCVTPH2PS(a
);
1026 FunctionType
* pFuncTy
= FunctionType::get(mFP32Ty
, mInt16Ty
);
1027 Function
* pCvtPh2Ps
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("ConvertFloat16ToFloat32", pFuncTy
));
1029 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertFloat16ToFloat32") == nullptr)
1031 sys::DynamicLibrary::AddSymbol("ConvertFloat16ToFloat32", (void *)&ConvertFloat16ToFloat32
);
1034 Value
* pResult
= UndefValue::get(mSimdFP32Ty
);
1035 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
1037 Value
* pSrc
= VEXTRACT(a
, C(i
));
1038 Value
* pConv
= CALL(pCvtPh2Ps
, std::initializer_list
<Value
*>{pSrc
});
1039 pResult
= VINSERT(pResult
, pConv
, C(i
));
1046 //////////////////////////////////////////////////////////////////////////
1047 /// @brief Generate a VCVTPS2PH operation (float32->float16 conversion)
1048 /// in LLVM IR. If not supported on the underlying platform, emulate it
1049 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
1050 Value
*Builder::CVTPS2PH(Value
* a
, Value
* rounding
)
1052 if (JM()->mArch
.F16C())
1054 return VCVTPS2PH(a
, rounding
);
1058 // call scalar C function for now
1059 FunctionType
* pFuncTy
= FunctionType::get(mInt16Ty
, mFP32Ty
);
1060 Function
* pCvtPs2Ph
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("ConvertFloat32ToFloat16", pFuncTy
));
1062 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertFloat32ToFloat16") == nullptr)
1064 sys::DynamicLibrary::AddSymbol("ConvertFloat32ToFloat16", (void *)&ConvertFloat32ToFloat16
);
1067 Value
* pResult
= UndefValue::get(mSimdInt16Ty
);
1068 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
1070 Value
* pSrc
= VEXTRACT(a
, C(i
));
1071 Value
* pConv
= CALL(pCvtPs2Ph
, std::initializer_list
<Value
*>{pSrc
});
1072 pResult
= VINSERT(pResult
, pConv
, C(i
));
1079 Value
*Builder::PMAXSD(Value
* a
, Value
* b
)
1081 Value
* cmp
= ICMP_SGT(a
, b
);
1082 return SELECT(cmp
, a
, b
);
1085 Value
*Builder::PMINSD(Value
* a
, Value
* b
)
1087 Value
* cmp
= ICMP_SLT(a
, b
);
1088 return SELECT(cmp
, a
, b
);
1091 void Builder::Gather4(const SWR_FORMAT format
, Value
* pSrcBase
, Value
* byteOffsets
,
1092 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
1094 const SWR_FORMAT_INFO
&info
= GetFormatInfo(format
);
1095 if(info
.type
[0] == SWR_TYPE_FLOAT
&& info
.bpc
[0] == 32)
1097 // ensure our mask is the correct type
1098 mask
= BITCAST(mask
, mSimdFP32Ty
);
1099 GATHER4PS(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
1103 // ensure our mask is the correct type
1104 mask
= BITCAST(mask
, mSimdInt32Ty
);
1105 GATHER4DD(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
1109 void Builder::GATHER4PS(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
1110 Value
* vMask
, Value
* vGatherComponents
[], bool bPackedOutput
)
1112 switch(info
.bpp
/ info
.numComps
)
1116 Value
* vGatherResult
[2];
1118 // TODO: vGatherMaskedVal
1119 Value
* vGatherMaskedVal
= VIMMED1((float)0);
1121 // always have at least one component out of x or y to fetch
1123 vGatherResult
[0] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
);
1124 // e.g. result of first 8x32bit integer gather for 16bit components
1125 // 256i - 0 1 2 3 4 5 6 7
1126 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
1129 // if we have at least one component out of x or y to fetch
1130 if(info
.numComps
> 2)
1132 // offset base to the next components(zw) in the vertex to gather
1133 pSrcBase
= GEP(pSrcBase
, C((char)4));
1135 vGatherResult
[1] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
);
1136 // e.g. result of second 8x32bit integer gather for 16bit components
1137 // 256i - 0 1 2 3 4 5 6 7
1138 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
1143 vGatherResult
[1] = vGatherMaskedVal
;
1146 // Shuffle gathered components into place, each row is a component
1147 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1153 for (uint32_t i
= 0; i
< 4; ++i
)
1155 vGatherComponents
[i
] = VIMMED1(*(float*)&info
.defaults
[i
]);
1158 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1160 uint32_t swizzleIndex
= info
.swizzle
[i
];
1162 // Gather a SIMD of components
1163 vGatherComponents
[swizzleIndex
] = GATHERPS(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
);
1165 // offset base to the next component to gather
1166 pSrcBase
= GEP(pSrcBase
, C((char)4));
1171 SWR_INVALID("Invalid float format");
1176 void Builder::GATHER4DD(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
1177 Value
* vMask
, Value
* vGatherComponents
[], bool bPackedOutput
)
1179 switch (info
.bpp
/ info
.numComps
)
1183 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1184 Value
* vGatherResult
= GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
);
1185 // e.g. result of an 8x32bit integer gather for 8bit components
1186 // 256i - 0 1 2 3 4 5 6 7
1187 // xyzw xyzw xyzw xyzw xyzw xyzw xyzw xyzw
1189 Shuffle8bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1194 Value
* vGatherResult
[2];
1196 // TODO: vGatherMaskedVal
1197 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1199 // always have at least one component out of x or y to fetch
1201 vGatherResult
[0] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
);
1202 // e.g. result of first 8x32bit integer gather for 16bit components
1203 // 256i - 0 1 2 3 4 5 6 7
1204 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
1207 // if we have at least one component out of x or y to fetch
1208 if(info
.numComps
> 2)
1210 // offset base to the next components(zw) in the vertex to gather
1211 pSrcBase
= GEP(pSrcBase
, C((char)4));
1213 vGatherResult
[1] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
);
1214 // e.g. result of second 8x32bit integer gather for 16bit components
1215 // 256i - 0 1 2 3 4 5 6 7
1216 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
1221 vGatherResult
[1] = vGatherMaskedVal
;
1224 // Shuffle gathered components into place, each row is a component
1225 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1232 for (uint32_t i
= 0; i
< 4; ++i
)
1234 vGatherComponents
[i
] = VIMMED1((int)info
.defaults
[i
]);
1237 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1239 uint32_t swizzleIndex
= info
.swizzle
[i
];
1241 // Gather a SIMD of components
1242 vGatherComponents
[swizzleIndex
] = GATHERDD(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
);
1244 // offset base to the next component to gather
1245 pSrcBase
= GEP(pSrcBase
, C((char)4));
1250 SWR_INVALID("unsupported format");
1255 void Builder::Shuffle16bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
[2], Value
* vGatherOutput
[4], bool bPackedOutput
)
1258 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1259 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4); // vwidth is units of 32 bits
1261 // input could either be float or int vector; do shuffle work in int
1262 vGatherInput
[0] = BITCAST(vGatherInput
[0], mSimdInt32Ty
);
1263 vGatherInput
[1] = BITCAST(vGatherInput
[1], mSimdInt32Ty
);
1267 Type
* v128bitTy
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1270 Value
* vConstMask
= C
<char>({0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
1271 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15});
1272 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[0], v32x8Ty
), vConstMask
), vGatherTy
);
1273 // after pshufb: group components together in each 128bit lane
1274 // 256i - 0 1 2 3 4 5 6 7
1275 // xxxx xxxx yyyy yyyy xxxx xxxx yyyy yyyy
1277 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1278 // after PERMD: move and pack xy components into each 128bit lane
1279 // 256i - 0 1 2 3 4 5 6 7
1280 // xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy
1282 // do the same for zw components
1283 Value
* vi128ZW
= nullptr;
1284 if(info
.numComps
> 2)
1286 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[1], v32x8Ty
), vConstMask
), vGatherTy
);
1287 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1290 for(uint32_t i
= 0; i
< 4; i
++)
1292 uint32_t swizzleIndex
= info
.swizzle
[i
];
1293 // todo: fixed for packed
1294 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1295 if(i
>= info
.numComps
)
1297 // set the default component val
1298 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1302 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1303 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1304 // if x or y, use vi128XY permute result, else use vi128ZW
1305 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1307 // extract packed component 128 bit lanes
1308 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1314 // pshufb masks for each component
1315 Value
* vConstMask
[2];
1317 vConstMask
[0] = C
<char>({0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1,
1318 0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1, });
1321 vConstMask
[1] = C
<char>({2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1,
1322 2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1});
1325 // shuffle enabled components into lower word of each 32bit lane, 0 extending to 32 bits
1327 for (uint32_t i
= 0; i
< 4; ++i
)
1329 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1332 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1334 uint32_t swizzleIndex
= info
.swizzle
[i
];
1336 // select correct constMask for x/z or y/w pshufb
1337 uint32_t selectedMask
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1338 // if x or y, use vi128XY permute result, else use vi128ZW
1339 uint32_t selectedGather
= (i
< 2) ? 0 : 1;
1341 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
[selectedGather
], v32x8Ty
), vConstMask
[selectedMask
]), vGatherTy
);
1342 // after pshufb mask for x channel; z uses the same shuffle from the second gather
1343 // 256i - 0 1 2 3 4 5 6 7
1344 // xx00 xx00 xx00 xx00 xx00 xx00 xx00 xx00
1349 void Builder::Shuffle8bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
, Value
* vGatherOutput
[], bool bPackedOutput
)
1352 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1353 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4 ); // vwidth is units of 32 bits
1357 Type
* v128Ty
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1359 Value
* vConstMask
= C
<char>({0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15,
1360 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15});
1361 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1362 // after pshufb: group components together in each 128bit lane
1363 // 256i - 0 1 2 3 4 5 6 7
1364 // xxxx yyyy zzzz wwww xxxx yyyy zzzz wwww
1366 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 4, 0, 0, 1, 5, 0, 0})), v128Ty
);
1367 // after PERMD: move and pack xy and zw components in low 64 bits of each 128bit lane
1368 // 256i - 0 1 2 3 4 5 6 7
1369 // xxxx xxxx dcdc dcdc yyyy yyyy dcdc dcdc (dc - don't care)
1371 // do the same for zw components
1372 Value
* vi128ZW
= nullptr;
1373 if(info
.numComps
> 2)
1375 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({2, 6, 0, 0, 3, 7, 0, 0})), v128Ty
);
1378 // sign extend all enabled components. If we have a fill vVertexElements, output to current simdvertex
1379 for(uint32_t i
= 0; i
< 4; i
++)
1381 uint32_t swizzleIndex
= info
.swizzle
[i
];
1382 // todo: fix for packed
1383 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1384 if(i
>= info
.numComps
)
1386 // set the default component val
1387 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1391 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1392 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1393 // if x or y, use vi128XY permute result, else use vi128ZW
1394 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1397 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1402 // shuffle enabled components into lower byte of each 32bit lane, 0 extending to 32 bits
1404 for (uint32_t i
= 0; i
< 4; ++i
)
1406 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1409 for(uint32_t i
= 0; i
< info
.numComps
; i
++){
1410 uint32_t swizzleIndex
= info
.swizzle
[i
];
1412 // pshufb masks for each component
1418 vConstMask
= C
<char>({0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1,
1419 0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1});
1423 vConstMask
= C
<char>({1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1,
1424 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1});
1428 vConstMask
= C
<char>({2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1,
1429 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1});
1433 vConstMask
= C
<char>({3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1,
1434 3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1});
1437 vConstMask
= nullptr;
1441 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1442 // after pshufb for x channel
1443 // 256i - 0 1 2 3 4 5 6 7
1444 // x000 x000 x000 x000 x000 x000 x000 x000
1449 // Helper function to create alloca in entry block of function
1450 Value
* Builder::CreateEntryAlloca(Function
* pFunc
, Type
* pType
)
1452 auto saveIP
= IRB()->saveIP();
1453 IRB()->SetInsertPoint(&pFunc
->getEntryBlock(),
1454 pFunc
->getEntryBlock().begin());
1455 Value
* pAlloca
= ALLOCA(pType
);
1456 if (saveIP
.isSet()) IRB()->restoreIP(saveIP
);
1460 Value
* Builder::CreateEntryAlloca(Function
* pFunc
, Type
* pType
, Value
* pArraySize
)
1462 auto saveIP
= IRB()->saveIP();
1463 IRB()->SetInsertPoint(&pFunc
->getEntryBlock(),
1464 pFunc
->getEntryBlock().begin());
1465 Value
* pAlloca
= ALLOCA(pType
, pArraySize
);
1466 if (saveIP
.isSet()) IRB()->restoreIP(saveIP
);
1470 //////////////////////////////////////////////////////////////////////////
1471 /// @brief emulates a scatter operation.
1472 /// @param pDst - pointer to destination
1473 /// @param vSrc - vector of src data to scatter
1474 /// @param vOffsets - vector of byte offsets from pDst
1475 /// @param vMask - mask of valid lanes
1476 void Builder::SCATTERPS(Value
* pDst
, Value
* vSrc
, Value
* vOffsets
, Value
* vMask
)
1478 /* Scatter algorithm
1480 while(Index = BitScanForward(mask))
1481 srcElem = srcVector[Index]
1482 offsetElem = offsetVector[Index]
1483 *(pDst + offsetElem) = srcElem
1484 Update mask (&= ~(1<<Index)
1488 BasicBlock
* pCurBB
= IRB()->GetInsertBlock();
1489 Function
* pFunc
= pCurBB
->getParent();
1490 Type
* pSrcTy
= vSrc
->getType()->getVectorElementType();
1492 // Store vectors on stack
1493 if (pScatterStackSrc
== nullptr)
1495 // Save off stack allocations and reuse per scatter. Significantly reduces stack
1496 // requirements for shaders with a lot of scatters.
1497 pScatterStackSrc
= CreateEntryAlloca(pFunc
, mSimdInt64Ty
);
1498 pScatterStackOffsets
= CreateEntryAlloca(pFunc
, mSimdInt32Ty
);
1501 Value
* pSrcArrayPtr
= BITCAST(pScatterStackSrc
, PointerType::get(vSrc
->getType(), 0));
1502 Value
* pOffsetsArrayPtr
= pScatterStackOffsets
;
1503 STORE(vSrc
, pSrcArrayPtr
);
1504 STORE(vOffsets
, pOffsetsArrayPtr
);
1506 // Cast to pointers for random access
1507 pSrcArrayPtr
= POINTER_CAST(pSrcArrayPtr
, PointerType::get(pSrcTy
, 0));
1508 pOffsetsArrayPtr
= POINTER_CAST(pOffsetsArrayPtr
, PointerType::get(mInt32Ty
, 0));
1510 Value
* pMask
= VMOVMSKPS(BITCAST(vMask
, mSimdFP32Ty
));
1512 // Get cttz function
1513 Function
* pfnCttz
= Intrinsic::getDeclaration(mpJitMgr
->mpCurrentModule
, Intrinsic::cttz
, { mInt32Ty
});
1515 // Setup loop basic block
1516 BasicBlock
* pLoop
= BasicBlock::Create(mpJitMgr
->mContext
, "Scatter Loop", pFunc
);
1518 // compute first set bit
1519 Value
* pIndex
= CALL(pfnCttz
, { pMask
, C(false) });
1521 Value
* pIsUndef
= ICMP_EQ(pIndex
, C(32));
1523 // Split current block
1524 BasicBlock
* pPostLoop
= pCurBB
->splitBasicBlock(cast
<Instruction
>(pIsUndef
)->getNextNode());
1526 // Remove unconditional jump created by splitBasicBlock
1527 pCurBB
->getTerminator()->eraseFromParent();
1529 // Add terminator to end of original block
1530 IRB()->SetInsertPoint(pCurBB
);
1532 // Add conditional branch
1533 COND_BR(pIsUndef
, pPostLoop
, pLoop
);
1535 // Add loop basic block contents
1536 IRB()->SetInsertPoint(pLoop
);
1537 PHINode
* pIndexPhi
= PHI(mInt32Ty
, 2);
1538 PHINode
* pMaskPhi
= PHI(mInt32Ty
, 2);
1540 pIndexPhi
->addIncoming(pIndex
, pCurBB
);
1541 pMaskPhi
->addIncoming(pMask
, pCurBB
);
1543 // Extract elements for this index
1544 Value
* pSrcElem
= LOADV(pSrcArrayPtr
, { pIndexPhi
});
1545 Value
* pOffsetElem
= LOADV(pOffsetsArrayPtr
, { pIndexPhi
});
1547 // GEP to this offset in dst
1548 Value
* pCurDst
= GEP(pDst
, pOffsetElem
);
1549 pCurDst
= POINTER_CAST(pCurDst
, PointerType::get(pSrcTy
, 0));
1550 STORE(pSrcElem
, pCurDst
);
1553 Value
* pNewMask
= AND(pMaskPhi
, NOT(SHL(C(1), pIndexPhi
)));
1556 Value
* pNewIndex
= CALL(pfnCttz
, { pNewMask
, C(false) });
1558 pIsUndef
= ICMP_EQ(pNewIndex
, C(32));
1559 COND_BR(pIsUndef
, pPostLoop
, pLoop
);
1562 pIndexPhi
->addIncoming(pNewIndex
, pLoop
);
1563 pMaskPhi
->addIncoming(pNewMask
, pLoop
);
1565 // Move builder to beginning of post loop
1566 IRB()->SetInsertPoint(pPostLoop
, pPostLoop
->begin());
1569 Value
* Builder::VABSPS(Value
* a
)
1571 Value
* asInt
= BITCAST(a
, mSimdInt32Ty
);
1572 Value
* result
= BITCAST(AND(asInt
, VIMMED1(0x7fffffff)), mSimdFP32Ty
);
1576 Value
*Builder::ICLAMP(Value
* src
, Value
* low
, Value
* high
)
1578 Value
*lowCmp
= ICMP_SLT(src
, low
);
1579 Value
*ret
= SELECT(lowCmp
, low
, src
);
1581 Value
*highCmp
= ICMP_SGT(ret
, high
);
1582 ret
= SELECT(highCmp
, high
, ret
);
1587 Value
*Builder::FCLAMP(Value
* src
, Value
* low
, Value
* high
)
1589 Value
*lowCmp
= FCMP_OLT(src
, low
);
1590 Value
*ret
= SELECT(lowCmp
, low
, src
);
1592 Value
*highCmp
= FCMP_OGT(ret
, high
);
1593 ret
= SELECT(highCmp
, high
, ret
);
1598 Value
*Builder::FCLAMP(Value
* src
, float low
, float high
)
1600 Value
* result
= VMAXPS(src
, VIMMED1(low
));
1601 result
= VMINPS(result
, VIMMED1(high
));
1606 //////////////////////////////////////////////////////////////////////////
1607 /// @brief save/restore stack, providing ability to push/pop the stack and
1608 /// reduce overall stack requirements for temporary stack use
1609 Value
* Builder::STACKSAVE()
1611 Function
* pfnStackSave
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stacksave
);
1612 return CALLA(pfnStackSave
);
1615 void Builder::STACKRESTORE(Value
* pSaved
)
1617 Function
* pfnStackRestore
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stackrestore
);
1618 CALL(pfnStackRestore
, std::initializer_list
<Value
*>{pSaved
});
1621 Value
*Builder::FMADDPS(Value
* a
, Value
* b
, Value
* c
)
1624 // use FMADs if available
1625 if(JM()->mArch
.AVX2())
1627 vOut
= VFMADDPS(a
, b
, c
);
1631 vOut
= FADD(FMUL(a
, b
), c
);
1636 Value
* Builder::POPCNT(Value
* a
)
1638 Function
* pCtPop
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::ctpop
, { a
->getType() });
1639 return CALL(pCtPop
, std::initializer_list
<Value
*>{a
});
1642 //////////////////////////////////////////////////////////////////////////
1643 /// @brief C functions called by LLVM IR
1644 //////////////////////////////////////////////////////////////////////////
1646 //////////////////////////////////////////////////////////////////////////
1647 /// @brief called in JIT code, inserted by PRINT
1648 /// output to both stdout and visual studio debug console
1649 void __cdecl
CallPrint(const char* fmt
, ...)
1652 va_start(args
, fmt
);
1655 #if defined( _WIN32 )
1657 vsnprintf_s(strBuf
, _TRUNCATE
, fmt
, args
);
1658 OutputDebugStringA(strBuf
);
1664 Value
*Builder::VEXTRACTI128(Value
* a
, Constant
* imm8
)
1666 bool flag
= !imm8
->isZeroValue();
1667 SmallVector
<Constant
*,8> idx
;
1668 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1669 idx
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1671 return VSHUFFLE(a
, VUNDEF_I(), ConstantVector::get(idx
));
1674 Value
*Builder::VINSERTI128(Value
* a
, Value
* b
, Constant
* imm8
)
1676 bool flag
= !imm8
->isZeroValue();
1677 SmallVector
<Constant
*,8> idx
;
1678 for (unsigned i
= 0; i
< mVWidth
; i
++) {
1679 idx
.push_back(C(i
));
1681 Value
*inter
= VSHUFFLE(b
, VUNDEF_I(), ConstantVector::get(idx
));
1683 SmallVector
<Constant
*,8> idx2
;
1684 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1685 idx2
.push_back(C(flag
? i
: i
+ mVWidth
));
1687 for (unsigned i
= mVWidth
/ 2; i
< mVWidth
; i
++) {
1688 idx2
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1690 return VSHUFFLE(a
, inter
, ConstantVector::get(idx2
));
1693 // rdtsc buckets macros
1694 void Builder::RDTSC_START(Value
* pBucketMgr
, Value
* pId
)
1696 // @todo due to an issue with thread local storage propagation in llvm, we can only safely call into
1697 // buckets framework when single threaded
1698 if (KNOB_SINGLE_THREADED
)
1700 std::vector
<Type
*> args
{
1701 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1705 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1706 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StartBucket", pFuncTy
));
1707 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StartBucket") == nullptr)
1709 sys::DynamicLibrary::AddSymbol("BucketManager_StartBucket", (void*)&BucketManager_StartBucket
);
1712 CALL(pFunc
, { pBucketMgr
, pId
});
1716 void Builder::RDTSC_STOP(Value
* pBucketMgr
, Value
* pId
)
1718 // @todo due to an issue with thread local storage propagation in llvm, we can only safely call into
1719 // buckets framework when single threaded
1720 if (KNOB_SINGLE_THREADED
)
1722 std::vector
<Type
*> args
{
1723 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1727 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1728 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StopBucket", pFuncTy
));
1729 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StopBucket") == nullptr)
1731 sys::DynamicLibrary::AddSymbol("BucketManager_StopBucket", (void*)&BucketManager_StopBucket
);
1734 CALL(pFunc
, { pBucketMgr
, pId
});
1739 uint32_t Builder::GetTypeSize(Type
* pType
)
1741 if (pType
->isStructTy())
1743 uint32_t numElems
= pType
->getStructNumElements();
1744 Type
* pElemTy
= pType
->getStructElementType(0);
1745 return numElems
* GetTypeSize(pElemTy
);
1748 if (pType
->isArrayTy())
1750 uint32_t numElems
= pType
->getArrayNumElements();
1751 Type
* pElemTy
= pType
->getArrayElementType();
1752 return numElems
* GetTypeSize(pElemTy
);
1755 if (pType
->isIntegerTy())
1757 uint32_t bitSize
= pType
->getIntegerBitWidth();
1761 if (pType
->isFloatTy())
1766 if (pType
->isHalfTy())
1771 if (pType
->isDoubleTy())
1776 SWR_ASSERT(false, "Unimplemented type.");