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"
33 #include "llvm/Support/DynamicLibrary.h"
35 void __cdecl
CallPrint(const char* fmt
, ...);
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
)
45 uint32_t sign
, exp
, mant
;
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;
54 // Check for out of range
59 sign
= 1; // set the sign bit for NANs
61 else if (std::isinf(val
))
66 else if (exp
> (0x70 + 0x1E)) // Too big to represent -> max representable value
71 else if ((exp
<= 0x70) && (exp
>= 0x66)) // It's a denorm
74 for (; exp
<= 0x70; mant
>>= 1, exp
++)
79 else if (exp
< 0x66) // Too small to represent -> Zero
86 // Saves bits that will be shifted off for rounding
87 roundBits
= mant
& 0x1FFFu
;
88 // convert exponent and mantissa to 16 bit format
92 // Essentially RTZ, but round up if off by only 1 lsb
93 if (roundBits
== 0x1FFFu
)
97 if ((mant
& 0xC00u
) != 0)
99 // make sure only the needed bits are used
104 uint32_t tmpVal
= (sign
<< 15) | (exp
<< 10) | mant
;
105 return (uint16_t)tmpVal
;
108 //////////////////////////////////////////////////////////////////////////
109 /// @brief Convert an IEEE 754 16-bit float to an 32-bit single precision
111 /// @param val - 16-bit float
112 /// @todo Maybe move this outside of this file into a header?
113 static float ConvertSmallFloatTo32(UINT val
)
116 if ((val
& 0x7fff) == 0)
118 result
= ((uint32_t)(val
& 0x8000)) << 16;
120 else if ((val
& 0x7c00) == 0x7c00)
122 result
= ((val
& 0x3ff) == 0) ? 0x7f800000 : 0x7fc00000;
123 result
|= ((uint32_t)val
& 0x8000) << 16;
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
133 while (mant
< (0x400 << 13))
138 mant
&= (0x3ff << 13);
140 exp
= ((exp
- 15 + 127) & 0xff) << 23;
141 result
= sign
| exp
| mant
;
144 return *(float*)&result
;
147 Constant
*Builder::C(bool i
)
149 return ConstantInt::get(IRB()->getInt1Ty(), (i
? 1 : 0));
152 Constant
*Builder::C(char i
)
154 return ConstantInt::get(IRB()->getInt8Ty(), i
);
157 Constant
*Builder::C(uint8_t i
)
159 return ConstantInt::get(IRB()->getInt8Ty(), i
);
162 Constant
*Builder::C(int i
)
164 return ConstantInt::get(IRB()->getInt32Ty(), i
);
167 Constant
*Builder::C(int64_t i
)
169 return ConstantInt::get(IRB()->getInt64Ty(), i
);
172 Constant
*Builder::C(uint16_t i
)
174 return ConstantInt::get(mInt16Ty
,i
);
177 Constant
*Builder::C(uint32_t i
)
179 return ConstantInt::get(IRB()->getInt32Ty(), i
);
182 Constant
*Builder::C(float i
)
184 return ConstantFP::get(IRB()->getFloatTy(), i
);
187 Constant
*Builder::PRED(bool pred
)
189 return ConstantInt::get(IRB()->getInt1Ty(), (pred
? 1 : 0));
192 Value
*Builder::VIMMED1(int i
)
194 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
197 Value
*Builder::VIMMED1(uint32_t i
)
199 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
202 Value
*Builder::VIMMED1(float i
)
204 return ConstantVector::getSplat(mVWidth
, cast
<ConstantFP
>(C(i
)));
207 Value
*Builder::VIMMED1(bool i
)
209 return ConstantVector::getSplat(mVWidth
, cast
<ConstantInt
>(C(i
)));
212 Value
*Builder::VUNDEF_IPTR()
214 return UndefValue::get(VectorType::get(mInt32PtrTy
,mVWidth
));
217 Value
*Builder::VUNDEF_I()
219 return UndefValue::get(VectorType::get(mInt32Ty
, mVWidth
));
222 Value
*Builder::VUNDEF(Type
*ty
, uint32_t size
)
224 return UndefValue::get(VectorType::get(ty
, size
));
227 Value
*Builder::VUNDEF_F()
229 return UndefValue::get(VectorType::get(mFP32Ty
, mVWidth
));
232 Value
*Builder::VUNDEF(Type
* t
)
234 return UndefValue::get(VectorType::get(t
, mVWidth
));
237 #if HAVE_LLVM == 0x306
238 Value
*Builder::VINSERT(Value
*vec
, Value
*val
, uint64_t index
)
240 return VINSERT(vec
, val
, C((int64_t)index
));
244 Value
*Builder::VBROADCAST(Value
*src
)
246 // check if src is already a vector
247 if (src
->getType()->isVectorTy())
252 return VECTOR_SPLAT(mVWidth
, src
);
255 uint32_t Builder::IMMED(Value
* v
)
257 SWR_ASSERT(isa
<ConstantInt
>(v
));
258 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
259 return pValConst
->getZExtValue();
262 int32_t Builder::S_IMMED(Value
* v
)
264 SWR_ASSERT(isa
<ConstantInt
>(v
));
265 ConstantInt
*pValConst
= cast
<ConstantInt
>(v
);
266 return pValConst
->getSExtValue();
269 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<Value
*> &indexList
)
271 std::vector
<Value
*> indices
;
272 for (auto i
: indexList
)
273 indices
.push_back(i
);
274 return GEPA(ptr
, indices
);
277 Value
*Builder::GEP(Value
* ptr
, const std::initializer_list
<uint32_t> &indexList
)
279 std::vector
<Value
*> indices
;
280 for (auto i
: indexList
)
281 indices
.push_back(C(i
));
282 return GEPA(ptr
, indices
);
285 LoadInst
*Builder::LOAD(Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
, const llvm::Twine
& name
)
287 std::vector
<Value
*> valIndices
;
288 for (auto i
: indices
)
289 valIndices
.push_back(C(i
));
290 return LOAD(GEPA(basePtr
, valIndices
), name
);
293 LoadInst
*Builder::LOADV(Value
*basePtr
, const std::initializer_list
<Value
*> &indices
, const llvm::Twine
& name
)
295 std::vector
<Value
*> valIndices
;
296 for (auto i
: indices
)
297 valIndices
.push_back(i
);
298 return LOAD(GEPA(basePtr
, valIndices
), name
);
301 StoreInst
*Builder::STORE(Value
*val
, Value
*basePtr
, const std::initializer_list
<uint32_t> &indices
)
303 std::vector
<Value
*> valIndices
;
304 for (auto i
: indices
)
305 valIndices
.push_back(C(i
));
306 return STORE(val
, GEPA(basePtr
, valIndices
));
309 StoreInst
*Builder::STOREV(Value
*val
, Value
*basePtr
, const std::initializer_list
<Value
*> &indices
)
311 std::vector
<Value
*> valIndices
;
312 for (auto i
: indices
)
313 valIndices
.push_back(i
);
314 return STORE(val
, GEPA(basePtr
, valIndices
));
317 CallInst
*Builder::CALL(Value
*Callee
, const std::initializer_list
<Value
*> &argsList
)
319 std::vector
<Value
*> args
;
320 for (auto arg
: argsList
)
322 return CALLA(Callee
, args
);
325 Value
*Builder::VRCP(Value
*va
)
327 return FDIV(VIMMED1(1.0f
), va
); // 1 / a
330 Value
*Builder::VPLANEPS(Value
* vA
, Value
* vB
, Value
* vC
, Value
* &vX
, Value
* &vY
)
332 Value
* vOut
= FMADDPS(vA
, vX
, vC
);
333 vOut
= FMADDPS(vB
, vY
, vOut
);
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
)
345 // use avx2 gather instruction is available
346 if(JM()->mArch
.AVX2())
348 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_avx2_maskload_d_256
);
349 vResult
= CALL(func
,{src
,mask
});
353 Function
*func
= Intrinsic::getDeclaration(JM()->mpCurrentModule
,Intrinsic::x86_avx_maskload_ps_256
);
354 Value
* fMask
= BITCAST(mask
,VectorType::get(mInt32Ty
,mVWidth
));
355 vResult
= BITCAST(CALL(func
,{src
,fMask
}), VectorType::get(mInt32Ty
,mVWidth
));
360 //////////////////////////////////////////////////////////////////////////
361 /// @brief insert a JIT call to CallPrint
362 /// - outputs formatted string to both stdout and VS output window
363 /// - DEBUG builds only
365 /// PRINT("index %d = 0x%p\n",{C(lane), pIndex});
366 /// where C(lane) creates a constant value to print, and pIndex is the Value*
367 /// result from a GEP, printing out the pointer to memory
368 /// @param printStr - constant string to print, which includes format specifiers
369 /// @param printArgs - initializer list of Value*'s to print to std out
370 CallInst
*Builder::PRINT(const std::string
&printStr
,const std::initializer_list
<Value
*> &printArgs
)
372 // push the arguments to CallPrint into a vector
373 std::vector
<Value
*> printCallArgs
;
374 // save room for the format string. we still need to modify it for vectors
375 printCallArgs
.resize(1);
377 // search through the format string for special processing
379 std::string
tempStr(printStr
);
380 pos
= tempStr
.find('%', pos
);
381 auto v
= printArgs
.begin();
383 while ((pos
!= std::string::npos
) && (v
!= printArgs
.end()))
386 Type
* pType
= pArg
->getType();
388 if (pType
->isVectorTy())
390 Type
* pContainedType
= pType
->getContainedType(0);
392 if (toupper(tempStr
[pos
+ 1]) == 'X')
395 tempStr
[pos
+ 1] = 'x';
396 tempStr
.insert(pos
+ 2, "%08X ");
399 printCallArgs
.push_back(VEXTRACT(pArg
, C(0)));
401 std::string vectorFormatStr
;
402 for (uint32_t i
= 1; i
< pType
->getVectorNumElements(); ++i
)
404 vectorFormatStr
+= "0x%08X ";
405 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
408 tempStr
.insert(pos
, vectorFormatStr
);
409 pos
+= vectorFormatStr
.size();
411 else if ((tempStr
[pos
+ 1] == 'f') && (pContainedType
->isFloatTy()))
414 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
416 tempStr
.insert(pos
, std::string("%f "));
418 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
420 printCallArgs
.push_back(FP_EXT(VEXTRACT(pArg
, C(i
)), Type::getDoubleTy(JM()->mContext
)));
422 else if ((tempStr
[pos
+ 1] == 'd') && (pContainedType
->isIntegerTy()))
425 for (; i
< (pArg
->getType()->getVectorNumElements()) - 1; i
++)
427 tempStr
.insert(pos
, std::string("%d "));
429 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
431 printCallArgs
.push_back(VEXTRACT(pArg
, C(i
)));
436 if (toupper(tempStr
[pos
+ 1]) == 'X')
439 tempStr
.insert(pos
+ 1, "x%08");
440 printCallArgs
.push_back(pArg
);
443 // for %f we need to cast float Values to doubles so that they print out correctly
444 else if ((tempStr
[pos
+ 1] == 'f') && (pType
->isFloatTy()))
446 printCallArgs
.push_back(FP_EXT(pArg
, Type::getDoubleTy(JM()->mContext
)));
451 printCallArgs
.push_back(pArg
);
455 // advance to the next arguement
457 pos
= tempStr
.find('%', ++pos
);
460 // create global variable constant string
461 Constant
*constString
= ConstantDataArray::getString(JM()->mContext
,tempStr
,true);
462 GlobalVariable
*gvPtr
= new GlobalVariable(constString
->getType(),true,GlobalValue::InternalLinkage
,constString
,"printStr");
463 JM()->mpCurrentModule
->getGlobalList().push_back(gvPtr
);
465 // get a pointer to the first character in the constant string array
466 std::vector
<Constant
*> geplist
{C(0),C(0)};
467 #if HAVE_LLVM == 0x306
468 Constant
*strGEP
= ConstantExpr::getGetElementPtr(gvPtr
,geplist
,false);
470 Constant
*strGEP
= ConstantExpr::getGetElementPtr(nullptr, gvPtr
,geplist
,false);
473 // insert the pointer to the format string in the argument vector
474 printCallArgs
[0] = strGEP
;
476 // get pointer to CallPrint function and insert decl into the module if needed
477 std::vector
<Type
*> args
;
478 args
.push_back(PointerType::get(mInt8Ty
,0));
479 FunctionType
* callPrintTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
),args
,true);
480 Function
*callPrintFn
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("CallPrint", callPrintTy
));
482 // if we haven't yet added the symbol to the symbol table
483 if((sys::DynamicLibrary::SearchForAddressOfSymbol("CallPrint")) == nullptr)
485 sys::DynamicLibrary::AddSymbol("CallPrint", (void *)&CallPrint
);
488 // insert a call to CallPrint
489 return CALLA(callPrintFn
,printCallArgs
);
492 //////////////////////////////////////////////////////////////////////////
493 /// @brief Wrapper around PRINT with initializer list.
494 CallInst
* Builder::PRINT(const std::string
&printStr
)
496 return PRINT(printStr
, {});
499 //////////////////////////////////////////////////////////////////////////
500 /// @brief Generate a masked gather operation in LLVM IR. If not
501 /// supported on the underlying platform, emulate it with loads
502 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
503 /// @param pBase - Int8* base VB address pointer value
504 /// @param vIndices - SIMD wide value of VB byte offsets
505 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
506 /// @param scale - value to scale indices by
507 Value
*Builder::GATHERPS(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, Value
* scale
)
511 // use avx2 gather instruction if available
512 if(JM()->mArch
.AVX2())
514 // force mask to <N x float>, required by vgather
515 vMask
= BITCAST(vMask
, mSimdFP32Ty
);
516 vGather
= VGATHERPS(vSrc
,pBase
,vIndices
,vMask
,scale
);
520 Value
* pStack
= STACKSAVE();
522 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
523 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
524 STORE(vSrc
, vSrcPtr
);
526 vGather
= VUNDEF_F();
527 Value
*vScaleVec
= VBROADCAST(Z_EXT(scale
,mInt32Ty
));
528 Value
*vOffsets
= MUL(vIndices
,vScaleVec
);
529 Value
*mask
= MASK(vMask
);
530 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
532 // single component byte index
533 Value
*offset
= VEXTRACT(vOffsets
,C(i
));
534 // byte pointer to component
535 Value
*loadAddress
= GEP(pBase
,offset
);
536 loadAddress
= BITCAST(loadAddress
,PointerType::get(mFP32Ty
,0));
537 // pointer to the value to load if we're masking off a component
538 Value
*maskLoadAddress
= GEP(vSrcPtr
,{C(0), C(i
)});
539 Value
*selMask
= VEXTRACT(mask
,C(i
));
540 // switch in a safe address to load if we're trying to access a vertex
541 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
542 Value
*val
= LOAD(validAddress
);
543 vGather
= VINSERT(vGather
,val
,C(i
));
545 STACKRESTORE(pStack
);
551 //////////////////////////////////////////////////////////////////////////
552 /// @brief Generate a masked gather operation in LLVM IR. If not
553 /// supported on the underlying platform, emulate it with loads
554 /// @param vSrc - SIMD wide value that will be loaded if mask is invalid
555 /// @param pBase - Int8* base VB address pointer value
556 /// @param vIndices - SIMD wide value of VB byte offsets
557 /// @param vMask - SIMD wide mask that controls whether to access memory or the src values
558 /// @param scale - value to scale indices by
559 Value
*Builder::GATHERDD(Value
* vSrc
, Value
* pBase
, Value
* vIndices
, Value
* vMask
, Value
* scale
)
563 // use avx2 gather instruction if available
564 if(JM()->mArch
.AVX2())
566 vGather
= VGATHERDD(vSrc
, pBase
, vIndices
, vMask
, scale
);
570 Value
* pStack
= STACKSAVE();
572 // store vSrc on the stack. this way we can select between a valid load address and the vSrc address
573 Value
* vSrcPtr
= ALLOCA(vSrc
->getType());
574 STORE(vSrc
, vSrcPtr
);
576 vGather
= VUNDEF_I();
577 Value
*vScaleVec
= VBROADCAST(Z_EXT(scale
, mInt32Ty
));
578 Value
*vOffsets
= MUL(vIndices
, vScaleVec
);
579 Value
*mask
= MASK(vMask
);
580 for(uint32_t i
= 0; i
< mVWidth
; ++i
)
582 // single component byte index
583 Value
*offset
= VEXTRACT(vOffsets
, C(i
));
584 // byte pointer to component
585 Value
*loadAddress
= GEP(pBase
, offset
);
586 loadAddress
= BITCAST(loadAddress
, PointerType::get(mInt32Ty
, 0));
587 // pointer to the value to load if we're masking off a component
588 Value
*maskLoadAddress
= GEP(vSrcPtr
, {C(0), C(i
)});
589 Value
*selMask
= VEXTRACT(mask
, C(i
));
590 // switch in a safe address to load if we're trying to access a vertex
591 Value
*validAddress
= SELECT(selMask
, loadAddress
, maskLoadAddress
);
592 Value
*val
= LOAD(validAddress
, C(0));
593 vGather
= VINSERT(vGather
, val
, C(i
));
596 STACKRESTORE(pStack
);
601 //////////////////////////////////////////////////////////////////////////
602 /// @brief convert x86 <N x float> mask to llvm <N x i1> mask
603 Value
* Builder::MASK(Value
* vmask
)
605 Value
* src
= BITCAST(vmask
, mSimdInt32Ty
);
606 return ICMP_SLT(src
, VIMMED1(0));
609 //////////////////////////////////////////////////////////////////////////
610 /// @brief convert llvm <N x i1> mask to x86 <N x i32> mask
611 Value
* Builder::VMASK(Value
* mask
)
613 return S_EXT(mask
, mSimdInt32Ty
);
616 //////////////////////////////////////////////////////////////////////////
617 /// @brief Generate a VPSHUFB operation in LLVM IR. If not
618 /// supported on the underlying platform, emulate it
619 /// @param a - 256bit SIMD(32x8bit) of 8bit integer values
620 /// @param b - 256bit SIMD(32x8bit) of 8bit integer mask values
621 /// Byte masks in lower 128 lane of b selects 8 bit values from lower
622 /// 128bits of a, and vice versa for the upper lanes. If the mask
623 /// value is negative, '0' is inserted.
624 Value
*Builder::PSHUFB(Value
* a
, Value
* b
)
627 // use avx2 pshufb instruction if available
628 if(JM()->mArch
.AVX2())
634 Constant
* cB
= dyn_cast
<Constant
>(b
);
635 // number of 8 bit elements in b
636 uint32_t numElms
= cast
<VectorType
>(cB
->getType())->getNumElements();
638 Value
* vShuf
= UndefValue::get(VectorType::get(mInt8Ty
, numElms
));
640 // insert an 8 bit value from the high and low lanes of a per loop iteration
642 for(uint32_t i
= 0; i
< numElms
; i
++)
644 ConstantInt
* cLow128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
));
645 ConstantInt
* cHigh128b
= cast
<ConstantInt
>(cB
->getAggregateElement(i
+ numElms
));
647 // extract values from constant mask
648 char valLow128bLane
= (char)(cLow128b
->getSExtValue());
649 char valHigh128bLane
= (char)(cHigh128b
->getSExtValue());
651 Value
* insertValLow128b
;
652 Value
* insertValHigh128b
;
654 // if the mask value is negative, insert a '0' in the respective output position
655 // otherwise, lookup the value at mask position (bits 3..0 of the respective mask byte) in a and insert in output vector
656 insertValLow128b
= (valLow128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valLow128bLane
& 0xF)));
657 insertValHigh128b
= (valHigh128bLane
< 0) ? C((char)0) : VEXTRACT(a
, C((valHigh128bLane
& 0xF) + numElms
));
659 vShuf
= VINSERT(vShuf
, insertValLow128b
, i
);
660 vShuf
= VINSERT(vShuf
, insertValHigh128b
, (i
+ numElms
));
667 //////////////////////////////////////////////////////////////////////////
668 /// @brief Generate a VPSHUFB operation (sign extend 8 8bit values to 32
669 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
670 /// @param a - 128bit SIMD lane(16x8bit) of 8bit integer values. Only
671 /// lower 8 values are used.
672 Value
*Builder::PMOVSXBD(Value
* a
)
675 // use avx2 byte sign extend instruction if available
676 if(JM()->mArch
.AVX2())
682 // VPMOVSXBD output type
683 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
684 // Extract 8 values from 128bit lane and sign extend
685 res
= S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
690 //////////////////////////////////////////////////////////////////////////
691 /// @brief Generate a VPSHUFB operation (sign extend 8 16bit values to 32
692 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
693 /// @param a - 128bit SIMD lane(8x16bit) of 16bit integer values.
694 Value
*Builder::PMOVSXWD(Value
* a
)
697 // use avx2 word sign extend if available
698 if(JM()->mArch
.AVX2())
704 // VPMOVSXWD output type
705 Type
* v8x32Ty
= VectorType::get(mInt32Ty
, 8);
706 // Extract 8 values from 128bit lane and sign extend
707 res
= S_EXT(VSHUFFLE(a
, a
, C
<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty
);
712 //////////////////////////////////////////////////////////////////////////
713 /// @brief Generate a VPERMD operation (shuffle 32 bit integer values
714 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
715 /// platform, emulate it
716 /// @param a - 256bit SIMD lane(8x32bit) of integer values.
717 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
718 Value
*Builder::PERMD(Value
* a
, Value
* idx
)
721 // use avx2 permute instruction if available
722 if(JM()->mArch
.AVX2())
724 // llvm 3.6.0 swapped the order of the args to vpermd
725 res
= VPERMD(idx
, a
);
729 if (isa
<Constant
>(idx
))
731 res
= VSHUFFLE(a
, a
, idx
);
736 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
738 Value
* pIndex
= VEXTRACT(idx
, C(l
));
739 Value
* pVal
= VEXTRACT(a
, pIndex
);
740 res
= VINSERT(res
, pVal
, C(l
));
747 //////////////////////////////////////////////////////////////////////////
748 /// @brief Generate a VPERMPS operation (shuffle 32 bit float values
749 /// across 128 bit lanes) in LLVM IR. If not supported on the underlying
750 /// platform, emulate it
751 /// @param a - 256bit SIMD lane(8x32bit) of float values.
752 /// @param idx - 256bit SIMD lane(8x32bit) of 3 bit lane index values
753 Value
*Builder::PERMPS(Value
* a
, Value
* idx
)
756 // use avx2 permute instruction if available
757 if (JM()->mArch
.AVX2())
759 // llvm 3.6.0 swapped the order of the args to vpermd
760 res
= VPERMPS(idx
, a
);
764 if (isa
<Constant
>(idx
))
766 res
= VSHUFFLE(a
, a
, idx
);
771 for (uint32_t l
= 0; l
< JM()->mVWidth
; ++l
)
773 Value
* pIndex
= VEXTRACT(idx
, C(l
));
774 Value
* pVal
= VEXTRACT(a
, pIndex
);
775 res
= VINSERT(res
, pVal
, C(l
));
783 //////////////////////////////////////////////////////////////////////////
784 /// @brief Generate a VCVTPH2PS operation (float16->float32 conversion)
785 /// in LLVM IR. If not supported on the underlying platform, emulate it
786 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
787 Value
*Builder::CVTPH2PS(Value
* a
)
789 if (JM()->mArch
.F16C())
795 FunctionType
* pFuncTy
= FunctionType::get(mFP32Ty
, mInt16Ty
);
796 Function
* pCvtPh2Ps
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("ConvertSmallFloatTo32", pFuncTy
));
798 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertSmallFloatTo32") == nullptr)
800 sys::DynamicLibrary::AddSymbol("ConvertSmallFloatTo32", (void *)&ConvertSmallFloatTo32
);
803 Value
* pResult
= UndefValue::get(mSimdFP32Ty
);
804 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
806 Value
* pSrc
= VEXTRACT(a
, C(i
));
807 Value
* pConv
= CALL(pCvtPh2Ps
, std::initializer_list
<Value
*>{pSrc
});
808 pResult
= VINSERT(pResult
, pConv
, C(i
));
815 //////////////////////////////////////////////////////////////////////////
816 /// @brief Generate a VCVTPS2PH operation (float32->float16 conversion)
817 /// in LLVM IR. If not supported on the underlying platform, emulate it
818 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
819 Value
*Builder::CVTPS2PH(Value
* a
, Value
* rounding
)
821 if (JM()->mArch
.F16C())
823 return VCVTPS2PH(a
, rounding
);
827 // call scalar C function for now
828 FunctionType
* pFuncTy
= FunctionType::get(mInt16Ty
, mFP32Ty
);
829 Function
* pCvtPs2Ph
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("Convert32To16Float", pFuncTy
));
831 if (sys::DynamicLibrary::SearchForAddressOfSymbol("Convert32To16Float") == nullptr)
833 sys::DynamicLibrary::AddSymbol("Convert32To16Float", (void *)&Convert32To16Float
);
836 Value
* pResult
= UndefValue::get(mSimdInt16Ty
);
837 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
839 Value
* pSrc
= VEXTRACT(a
, C(i
));
840 Value
* pConv
= CALL(pCvtPs2Ph
, std::initializer_list
<Value
*>{pSrc
});
841 pResult
= VINSERT(pResult
, pConv
, C(i
));
848 Value
*Builder::PMAXSD(Value
* a
, Value
* b
)
850 if (JM()->mArch
.AVX2())
852 return VPMAXSD(a
, b
);
856 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
857 Function
* pmaxsd
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_sse41_pmaxsd
);
860 Value
* aLo
= VEXTRACTI128(a
, C((uint8_t)0));
861 Value
* bLo
= VEXTRACTI128(b
, C((uint8_t)0));
862 Value
* resLo
= CALL(pmaxsd
, {aLo
, bLo
});
865 Value
* aHi
= VEXTRACTI128(a
, C((uint8_t)1));
866 Value
* bHi
= VEXTRACTI128(b
, C((uint8_t)1));
867 Value
* resHi
= CALL(pmaxsd
, {aHi
, bHi
});
870 Value
* result
= VINSERTI128(VUNDEF_I(), resLo
, C((uint8_t)0));
871 result
= VINSERTI128(result
, resHi
, C((uint8_t)1));
877 Value
*Builder::PMINSD(Value
* a
, Value
* b
)
879 if (JM()->mArch
.AVX2())
881 return VPMINSD(a
, b
);
885 // use 4-wide sse max intrinsic on lower/upper halves of 8-wide sources
886 Function
* pminsd
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::x86_sse41_pminsd
);
889 Value
* aLo
= VEXTRACTI128(a
, C((uint8_t)0));
890 Value
* bLo
= VEXTRACTI128(b
, C((uint8_t)0));
891 Value
* resLo
= CALL(pminsd
, {aLo
, bLo
});
894 Value
* aHi
= VEXTRACTI128(a
, C((uint8_t)1));
895 Value
* bHi
= VEXTRACTI128(b
, C((uint8_t)1));
896 Value
* resHi
= CALL(pminsd
, {aHi
, bHi
});
899 Value
* result
= VINSERTI128(VUNDEF_I(), resLo
, C((uint8_t)0));
900 result
= VINSERTI128(result
, resHi
, C((uint8_t)1));
906 void Builder::Gather4(const SWR_FORMAT format
, Value
* pSrcBase
, Value
* byteOffsets
,
907 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
909 const SWR_FORMAT_INFO
&info
= GetFormatInfo(format
);
910 if(info
.type
[0] == SWR_TYPE_FLOAT
&& info
.bpc
[0] == 32)
912 // ensure our mask is the correct type
913 mask
= BITCAST(mask
, mSimdFP32Ty
);
914 GATHER4PS(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
918 // ensure our mask is the correct type
919 mask
= BITCAST(mask
, mSimdInt32Ty
);
920 GATHER4DD(info
, pSrcBase
, byteOffsets
, mask
, vGatherComponents
, bPackedOutput
);
924 void Builder::GATHER4PS(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
925 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
927 switch(info
.bpp
/ info
.numComps
)
931 Value
* vGatherResult
[2];
934 // TODO: vGatherMaskedVal
935 Value
* vGatherMaskedVal
= VIMMED1((float)0);
937 // always have at least one component out of x or y to fetch
939 // save mask as it is zero'd out after each gather
942 vGatherResult
[0] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
943 // e.g. result of first 8x32bit integer gather for 16bit components
944 // 256i - 0 1 2 3 4 5 6 7
945 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
948 // if we have at least one component out of x or y to fetch
949 if(info
.numComps
> 2)
951 // offset base to the next components(zw) in the vertex to gather
952 pSrcBase
= GEP(pSrcBase
, C((char)4));
955 vGatherResult
[1] = GATHERPS(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
956 // e.g. result of second 8x32bit integer gather for 16bit components
957 // 256i - 0 1 2 3 4 5 6 7
958 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
963 vGatherResult
[1] = vGatherMaskedVal
;
966 // Shuffle gathered components into place, each row is a component
967 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
973 for (uint32_t i
= 0; i
< 4; ++i
)
975 vGatherComponents
[i
] = VIMMED1(*(float*)&info
.defaults
[i
]);
978 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
980 uint32_t swizzleIndex
= info
.swizzle
[i
];
982 // save mask as it is zero'd out after each gather
985 // Gather a SIMD of components
986 vGatherComponents
[swizzleIndex
] = GATHERPS(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
, C((char)1));
988 // offset base to the next component to gather
989 pSrcBase
= GEP(pSrcBase
, C((char)4));
994 SWR_ASSERT(0, "Invalid float format");
999 void Builder::GATHER4DD(const SWR_FORMAT_INFO
&info
, Value
* pSrcBase
, Value
* byteOffsets
,
1000 Value
* mask
, Value
* vGatherComponents
[], bool bPackedOutput
)
1002 switch (info
.bpp
/ info
.numComps
)
1006 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1007 Value
* vGatherResult
= GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, mask
, C((char)1));
1008 // e.g. result of an 8x32bit integer gather for 8bit components
1009 // 256i - 0 1 2 3 4 5 6 7
1010 // xyzw xyzw xyzw xyzw xyzw xyzw xyzw xyzw
1012 Shuffle8bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1017 Value
* vGatherResult
[2];
1020 // TODO: vGatherMaskedVal
1021 Value
* vGatherMaskedVal
= VIMMED1((int32_t)0);
1023 // always have at least one component out of x or y to fetch
1025 // save mask as it is zero'd out after each gather
1028 vGatherResult
[0] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
1029 // e.g. result of first 8x32bit integer gather for 16bit components
1030 // 256i - 0 1 2 3 4 5 6 7
1031 // xyxy xyxy xyxy xyxy xyxy xyxy xyxy xyxy
1034 // if we have at least one component out of x or y to fetch
1035 if(info
.numComps
> 2)
1037 // offset base to the next components(zw) in the vertex to gather
1038 pSrcBase
= GEP(pSrcBase
, C((char)4));
1041 vGatherResult
[1] = GATHERDD(vGatherMaskedVal
, pSrcBase
, byteOffsets
, vMask
, C((char)1));
1042 // e.g. result of second 8x32bit integer gather for 16bit components
1043 // 256i - 0 1 2 3 4 5 6 7
1044 // zwzw zwzw zwzw zwzw zwzw zwzw zwzw zwzw
1049 vGatherResult
[1] = vGatherMaskedVal
;
1052 // Shuffle gathered components into place, each row is a component
1053 Shuffle16bpcGather4(info
, vGatherResult
, vGatherComponents
, bPackedOutput
);
1060 for (uint32_t i
= 0; i
< 4; ++i
)
1062 vGatherComponents
[i
] = VIMMED1((int)info
.defaults
[i
]);
1065 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1067 uint32_t swizzleIndex
= info
.swizzle
[i
];
1069 // save mask as it is zero'd out after each gather
1070 Value
*vMask
= mask
;
1072 // Gather a SIMD of components
1073 vGatherComponents
[swizzleIndex
] = GATHERDD(vGatherComponents
[swizzleIndex
], pSrcBase
, byteOffsets
, vMask
, C((char)1));
1075 // offset base to the next component to gather
1076 pSrcBase
= GEP(pSrcBase
, C((char)4));
1081 SWR_ASSERT(0, "unsupported format");
1086 void Builder::Shuffle16bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
[2], Value
* vGatherOutput
[4], bool bPackedOutput
)
1089 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1090 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4); // vwidth is units of 32 bits
1092 // input could either be float or int vector; do shuffle work in int
1093 vGatherInput
[0] = BITCAST(vGatherInput
[0], mSimdInt32Ty
);
1094 vGatherInput
[1] = BITCAST(vGatherInput
[1], mSimdInt32Ty
);
1098 Type
* v128bitTy
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1101 Value
* vConstMask
= C
<char>({0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15,
1102 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15});
1103 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[0], v32x8Ty
), vConstMask
), vGatherTy
);
1104 // after pshufb: group components together in each 128bit lane
1105 // 256i - 0 1 2 3 4 5 6 7
1106 // xxxx xxxx yyyy yyyy xxxx xxxx yyyy yyyy
1108 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1109 // after PERMD: move and pack xy components into each 128bit lane
1110 // 256i - 0 1 2 3 4 5 6 7
1111 // xxxx xxxx xxxx xxxx yyyy yyyy yyyy yyyy
1113 // do the same for zw components
1114 Value
* vi128ZW
= nullptr;
1115 if(info
.numComps
> 2)
1117 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
[1], v32x8Ty
), vConstMask
), vGatherTy
);
1118 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 1, 4, 5, 2, 3, 6, 7})), v128bitTy
);
1121 for(uint32_t i
= 0; i
< 4; i
++)
1123 uint32_t swizzleIndex
= info
.swizzle
[i
];
1124 // todo: fixed for packed
1125 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1126 if(i
>= info
.numComps
)
1128 // set the default component val
1129 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1133 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1134 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1135 // if x or y, use vi128XY permute result, else use vi128ZW
1136 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1138 // extract packed component 128 bit lanes
1139 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1145 // pshufb masks for each component
1146 Value
* vConstMask
[2];
1148 vConstMask
[0] = C
<char>({0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1,
1149 0, 1, -1, -1, 4, 5, -1, -1, 8, 9, -1, -1, 12, 13, -1, -1, });
1152 vConstMask
[1] = C
<char>({2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1,
1153 2, 3, -1, -1, 6, 7, -1, -1, 10, 11, -1, -1, 14, 15, -1, -1});
1156 // shuffle enabled components into lower word of each 32bit lane, 0 extending to 32 bits
1158 for (uint32_t i
= 0; i
< 4; ++i
)
1160 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1163 for(uint32_t i
= 0; i
< info
.numComps
; i
++)
1165 uint32_t swizzleIndex
= info
.swizzle
[i
];
1167 // select correct constMask for x/z or y/w pshufb
1168 uint32_t selectedMask
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1169 // if x or y, use vi128XY permute result, else use vi128ZW
1170 uint32_t selectedGather
= (i
< 2) ? 0 : 1;
1172 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
[selectedGather
], v32x8Ty
), vConstMask
[selectedMask
]), vGatherTy
);
1173 // after pshufb mask for x channel; z uses the same shuffle from the second gather
1174 // 256i - 0 1 2 3 4 5 6 7
1175 // xx00 xx00 xx00 xx00 xx00 xx00 xx00 xx00
1180 void Builder::Shuffle8bpcGather4(const SWR_FORMAT_INFO
&info
, Value
* vGatherInput
, Value
* vGatherOutput
[], bool bPackedOutput
)
1183 Type
* vGatherTy
= VectorType::get(IntegerType::getInt32Ty(JM()->mContext
), mVWidth
);
1184 Type
* v32x8Ty
= VectorType::get(mInt8Ty
, mVWidth
* 4 ); // vwidth is units of 32 bits
1188 Type
* v128Ty
= VectorType::get(IntegerType::getIntNTy(JM()->mContext
, 128), mVWidth
/ 4); // vwidth is units of 32 bits
1190 Value
* vConstMask
= C
<char>({0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15,
1191 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15});
1192 Value
* vShufResult
= BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1193 // after pshufb: group components together in each 128bit lane
1194 // 256i - 0 1 2 3 4 5 6 7
1195 // xxxx yyyy zzzz wwww xxxx yyyy zzzz wwww
1197 Value
* vi128XY
= BITCAST(PERMD(vShufResult
, C
<int32_t>({0, 4, 0, 0, 1, 5, 0, 0})), v128Ty
);
1198 // after PERMD: move and pack xy and zw components in low 64 bits of each 128bit lane
1199 // 256i - 0 1 2 3 4 5 6 7
1200 // xxxx xxxx dcdc dcdc yyyy yyyy dcdc dcdc (dc - don't care)
1202 // do the same for zw components
1203 Value
* vi128ZW
= nullptr;
1204 if(info
.numComps
> 2)
1206 vi128ZW
= BITCAST(PERMD(vShufResult
, C
<int32_t>({2, 6, 0, 0, 3, 7, 0, 0})), v128Ty
);
1209 // sign extend all enabled components. If we have a fill vVertexElements, output to current simdvertex
1210 for(uint32_t i
= 0; i
< 4; i
++)
1212 uint32_t swizzleIndex
= info
.swizzle
[i
];
1213 // todo: fix for packed
1214 Value
* vGatherMaskedVal
= VIMMED1((int32_t)(info
.defaults
[i
]));
1215 if(i
>= info
.numComps
)
1217 // set the default component val
1218 vGatherOutput
[swizzleIndex
] = vGatherMaskedVal
;
1222 // if x or z, extract 128bits from lane 0, else for y or w, extract from lane 1
1223 uint32_t lane
= ((i
== 0) || (i
== 2)) ? 0 : 1;
1224 // if x or y, use vi128XY permute result, else use vi128ZW
1225 Value
* selectedPermute
= (i
< 2) ? vi128XY
: vi128ZW
;
1228 vGatherOutput
[swizzleIndex
] = VEXTRACT(selectedPermute
, C(lane
));
1233 // shuffle enabled components into lower byte of each 32bit lane, 0 extending to 32 bits
1235 for (uint32_t i
= 0; i
< 4; ++i
)
1237 vGatherOutput
[i
] = VIMMED1((int32_t)info
.defaults
[i
]);
1240 for(uint32_t i
= 0; i
< info
.numComps
; i
++){
1241 uint32_t swizzleIndex
= info
.swizzle
[i
];
1243 // pshufb masks for each component
1249 vConstMask
= C
<char>({0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1,
1250 0, -1, -1, -1, 4, -1, -1, -1, 8, -1, -1, -1, 12, -1, -1, -1});
1254 vConstMask
= C
<char>({1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1,
1255 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1});
1259 vConstMask
= C
<char>({2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1,
1260 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1});
1264 vConstMask
= C
<char>({3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1,
1265 3, -1, -1, -1, 7, -1, -1, -1, 11, -1, -1, -1, 15, -1, -1, -1});
1268 vConstMask
= nullptr;
1272 vGatherOutput
[swizzleIndex
] = BITCAST(PSHUFB(BITCAST(vGatherInput
, v32x8Ty
), vConstMask
), vGatherTy
);
1273 // after pshufb for x channel
1274 // 256i - 0 1 2 3 4 5 6 7
1275 // x000 x000 x000 x000 x000 x000 x000 x000
1280 //////////////////////////////////////////////////////////////////////////
1281 /// @brief emulates a scatter operation.
1282 /// @param pDst - pointer to destination
1283 /// @param vSrc - vector of src data to scatter
1284 /// @param vOffsets - vector of byte offsets from pDst
1285 /// @param vMask - mask of valid lanes
1286 void Builder::SCATTERPS(Value
* pDst
, Value
* vSrc
, Value
* vOffsets
, Value
* vMask
)
1288 Value
* pStack
= STACKSAVE();
1290 Type
* pSrcTy
= vSrc
->getType()->getVectorElementType();
1292 // allocate tmp stack for masked off lanes
1293 Value
* vTmpPtr
= ALLOCA(pSrcTy
);
1295 Value
*mask
= MASK(vMask
);
1296 for (uint32_t i
= 0; i
< mVWidth
; ++i
)
1298 Value
*offset
= VEXTRACT(vOffsets
, C(i
));
1299 // byte pointer to component
1300 Value
*storeAddress
= GEP(pDst
, offset
);
1301 storeAddress
= BITCAST(storeAddress
, PointerType::get(pSrcTy
, 0));
1302 Value
*selMask
= VEXTRACT(mask
, C(i
));
1303 Value
*srcElem
= VEXTRACT(vSrc
, C(i
));
1304 // switch in a safe address to load if we're trying to access a vertex
1305 Value
*validAddress
= SELECT(selMask
, storeAddress
, vTmpPtr
);
1306 STORE(srcElem
, validAddress
);
1309 STACKRESTORE(pStack
);
1312 Value
* Builder::VABSPS(Value
* a
)
1314 Value
* asInt
= BITCAST(a
, mSimdInt32Ty
);
1315 Value
* result
= BITCAST(AND(asInt
, VIMMED1(0x7fffffff)), mSimdFP32Ty
);
1319 Value
*Builder::ICLAMP(Value
* src
, Value
* low
, Value
* high
)
1321 Value
*lowCmp
= ICMP_SLT(src
, low
);
1322 Value
*ret
= SELECT(lowCmp
, low
, src
);
1324 Value
*highCmp
= ICMP_SGT(ret
, high
);
1325 ret
= SELECT(highCmp
, high
, ret
);
1330 Value
*Builder::FCLAMP(Value
* src
, Value
* low
, Value
* high
)
1332 Value
*lowCmp
= FCMP_OLT(src
, low
);
1333 Value
*ret
= SELECT(lowCmp
, low
, src
);
1335 Value
*highCmp
= FCMP_OGT(ret
, high
);
1336 ret
= SELECT(highCmp
, high
, ret
);
1341 Value
*Builder::FCLAMP(Value
* src
, float low
, float high
)
1343 Value
* result
= VMAXPS(src
, VIMMED1(low
));
1344 result
= VMINPS(result
, VIMMED1(high
));
1349 //////////////////////////////////////////////////////////////////////////
1350 /// @brief save/restore stack, providing ability to push/pop the stack and
1351 /// reduce overall stack requirements for temporary stack use
1352 Value
* Builder::STACKSAVE()
1354 Function
* pfnStackSave
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stacksave
);
1355 #if HAVE_LLVM == 0x306
1356 return CALL(pfnStackSave
);
1358 return CALLA(pfnStackSave
);
1362 void Builder::STACKRESTORE(Value
* pSaved
)
1364 Function
* pfnStackRestore
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::stackrestore
);
1365 CALL(pfnStackRestore
, std::initializer_list
<Value
*>{pSaved
});
1368 Value
*Builder::FMADDPS(Value
* a
, Value
* b
, Value
* c
)
1371 // use FMADs if available
1372 if(JM()->mArch
.AVX2())
1374 vOut
= VFMADDPS(a
, b
, c
);
1378 vOut
= FADD(FMUL(a
, b
), c
);
1383 Value
* Builder::POPCNT(Value
* a
)
1385 Function
* pCtPop
= Intrinsic::getDeclaration(JM()->mpCurrentModule
, Intrinsic::ctpop
, { a
->getType() });
1386 return CALL(pCtPop
, std::initializer_list
<Value
*>{a
});
1389 //////////////////////////////////////////////////////////////////////////
1390 /// @brief C functions called by LLVM IR
1391 //////////////////////////////////////////////////////////////////////////
1393 //////////////////////////////////////////////////////////////////////////
1394 /// @brief called in JIT code, inserted by PRINT
1395 /// output to both stdout and visual studio debug console
1396 void __cdecl
CallPrint(const char* fmt
, ...)
1399 va_start(args
, fmt
);
1402 #if defined( _WIN32 )
1404 vsnprintf_s(strBuf
, _TRUNCATE
, fmt
, args
);
1405 OutputDebugString(strBuf
);
1411 Value
*Builder::VEXTRACTI128(Value
* a
, Constant
* imm8
)
1413 #if HAVE_LLVM == 0x306
1415 Intrinsic::getDeclaration(JM()->mpCurrentModule
,
1416 Intrinsic::x86_avx_vextractf128_si_256
);
1417 return CALL(func
, {a
, imm8
});
1419 bool flag
= !imm8
->isZeroValue();
1420 SmallVector
<Constant
*,8> idx
;
1421 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1422 idx
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1424 return VSHUFFLE(a
, VUNDEF_I(), ConstantVector::get(idx
));
1428 Value
*Builder::VINSERTI128(Value
* a
, Value
* b
, Constant
* imm8
)
1430 #if HAVE_LLVM == 0x306
1432 Intrinsic::getDeclaration(JM()->mpCurrentModule
,
1433 Intrinsic::x86_avx_vinsertf128_si_256
);
1434 return CALL(func
, {a
, b
, imm8
});
1436 bool flag
= !imm8
->isZeroValue();
1437 SmallVector
<Constant
*,8> idx
;
1438 for (unsigned i
= 0; i
< mVWidth
; i
++) {
1439 idx
.push_back(C(i
));
1441 Value
*inter
= VSHUFFLE(b
, VUNDEF_I(), ConstantVector::get(idx
));
1443 SmallVector
<Constant
*,8> idx2
;
1444 for (unsigned i
= 0; i
< mVWidth
/ 2; i
++) {
1445 idx2
.push_back(C(flag
? i
: i
+ mVWidth
));
1447 for (unsigned i
= mVWidth
/ 2; i
< mVWidth
; i
++) {
1448 idx2
.push_back(C(flag
? i
+ mVWidth
/ 2 : i
));
1450 return VSHUFFLE(a
, inter
, ConstantVector::get(idx2
));
1454 // rdtsc buckets macros
1455 void Builder::RDTSC_START(Value
* pBucketMgr
, Value
* pId
)
1457 std::vector
<Type
*> args
{
1458 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1462 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1463 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StartBucket", pFuncTy
));
1464 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StartBucket") == nullptr)
1466 sys::DynamicLibrary::AddSymbol("BucketManager_StartBucket", (void*)&BucketManager_StartBucket
);
1469 CALL(pFunc
, { pBucketMgr
, pId
});
1472 void Builder::RDTSC_STOP(Value
* pBucketMgr
, Value
* pId
)
1474 std::vector
<Type
*> args
{
1475 PointerType::get(mInt32Ty
, 0), // pBucketMgr
1479 FunctionType
* pFuncTy
= FunctionType::get(Type::getVoidTy(JM()->mContext
), args
, false);
1480 Function
* pFunc
= cast
<Function
>(JM()->mpCurrentModule
->getOrInsertFunction("BucketManager_StopBucket", pFuncTy
));
1481 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StopBucket") == nullptr)
1483 sys::DynamicLibrary::AddSymbol("BucketManager_StopBucket", (void*)&BucketManager_StopBucket
);
1486 CALL(pFunc
, { pBucketMgr
, pId
});