swr/rast: Add constant initializer for uint64_t
[mesa.git] / src / gallium / drivers / swr / rasterizer / jitter / builder_misc.cpp
1 /****************************************************************************
2 * Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * @file builder_misc.cpp
24 *
25 * @brief Implementation for miscellaneous builder functions
26 *
27 * Notes:
28 *
29 ******************************************************************************/
30 #include "jit_pch.hpp"
31 #include "builder.h"
32 #include "common/rdtsc_buckets.h"
33
34 #include <cstdarg>
35
36 extern "C" void CallPrint(const char* fmt, ...);
37
38 namespace SwrJit
39 {
40 //////////////////////////////////////////////////////////////////////////
41 /// @brief Convert an IEEE 754 32-bit single precision float to an
42 /// 16 bit float with 5 exponent bits and a variable
43 /// number of mantissa bits.
44 /// @param val - 32-bit float
45 /// @todo Maybe move this outside of this file into a header?
46 static uint16_t ConvertFloat32ToFloat16(float val)
47 {
48 uint32_t sign, exp, mant;
49 uint32_t roundBits;
50
51 // Extract the sign, exponent, and mantissa
52 uint32_t uf = *(uint32_t*)&val;
53 sign = (uf & 0x80000000) >> 31;
54 exp = (uf & 0x7F800000) >> 23;
55 mant = uf & 0x007FFFFF;
56
57 // Check for out of range
58 if (std::isnan(val))
59 {
60 exp = 0x1F;
61 mant = 0x200;
62 sign = 1; // set the sign bit for NANs
63 }
64 else if (std::isinf(val))
65 {
66 exp = 0x1f;
67 mant = 0x0;
68 }
69 else if (exp > (0x70 + 0x1E)) // Too big to represent -> max representable value
70 {
71 exp = 0x1E;
72 mant = 0x3FF;
73 }
74 else if ((exp <= 0x70) && (exp >= 0x66)) // It's a denorm
75 {
76 mant |= 0x00800000;
77 for (; exp <= 0x70; mant >>= 1, exp++)
78 ;
79 exp = 0;
80 mant = mant >> 13;
81 }
82 else if (exp < 0x66) // Too small to represent -> Zero
83 {
84 exp = 0;
85 mant = 0;
86 }
87 else
88 {
89 // Saves bits that will be shifted off for rounding
90 roundBits = mant & 0x1FFFu;
91 // convert exponent and mantissa to 16 bit format
92 exp = exp - 0x70;
93 mant = mant >> 13;
94
95 // Essentially RTZ, but round up if off by only 1 lsb
96 if (roundBits == 0x1FFFu)
97 {
98 mant++;
99 // check for overflow
100 if ((mant & 0xC00u) != 0)
101 exp++;
102 // make sure only the needed bits are used
103 mant &= 0x3FF;
104 }
105 }
106
107 uint32_t tmpVal = (sign << 15) | (exp << 10) | mant;
108 return (uint16_t)tmpVal;
109 }
110
111 //////////////////////////////////////////////////////////////////////////
112 /// @brief Convert an IEEE 754 16-bit float to an 32-bit single precision
113 /// float
114 /// @param val - 16-bit float
115 /// @todo Maybe move this outside of this file into a header?
116 static float ConvertFloat16ToFloat32(uint32_t val)
117 {
118 uint32_t result;
119 if ((val & 0x7fff) == 0)
120 {
121 result = ((uint32_t)(val & 0x8000)) << 16;
122 }
123 else if ((val & 0x7c00) == 0x7c00)
124 {
125 result = ((val & 0x3ff) == 0) ? 0x7f800000 : 0x7fc00000;
126 result |= ((uint32_t)val & 0x8000) << 16;
127 }
128 else
129 {
130 uint32_t sign = (val & 0x8000) << 16;
131 uint32_t mant = (val & 0x3ff) << 13;
132 uint32_t exp = (val >> 10) & 0x1f;
133 if ((exp == 0) && (mant != 0)) // Adjust exponent and mantissa for denormals
134 {
135 mant <<= 1;
136 while (mant < (0x400 << 13))
137 {
138 exp--;
139 mant <<= 1;
140 }
141 mant &= (0x3ff << 13);
142 }
143 exp = ((exp - 15 + 127) & 0xff) << 23;
144 result = sign | exp | mant;
145 }
146
147 return *(float*)&result;
148 }
149
150 Constant *Builder::C(bool i)
151 {
152 return ConstantInt::get(IRB()->getInt1Ty(), (i ? 1 : 0));
153 }
154
155 Constant *Builder::C(char i)
156 {
157 return ConstantInt::get(IRB()->getInt8Ty(), i);
158 }
159
160 Constant *Builder::C(uint8_t i)
161 {
162 return ConstantInt::get(IRB()->getInt8Ty(), i);
163 }
164
165 Constant *Builder::C(int i)
166 {
167 return ConstantInt::get(IRB()->getInt32Ty(), i);
168 }
169
170 Constant *Builder::C(int64_t i)
171 {
172 return ConstantInt::get(IRB()->getInt64Ty(), i);
173 }
174
175 Constant *Builder::C(uint16_t i)
176 {
177 return ConstantInt::get(mInt16Ty,i);
178 }
179
180 Constant *Builder::C(uint32_t i)
181 {
182 return ConstantInt::get(IRB()->getInt32Ty(), i);
183 }
184
185 Constant *Builder::C(uint64_t i)
186 {
187 return ConstantInt::get(IRB()->getInt64Ty(), i);
188 }
189
190 Constant *Builder::C(float i)
191 {
192 return ConstantFP::get(IRB()->getFloatTy(), i);
193 }
194
195 Constant *Builder::PRED(bool pred)
196 {
197 return ConstantInt::get(IRB()->getInt1Ty(), (pred ? 1 : 0));
198 }
199
200 Value *Builder::VIMMED1(int i)
201 {
202 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
203 }
204
205 Value *Builder::VIMMED1_16(int i)
206 {
207 return ConstantVector::getSplat(mVWidth16, cast<ConstantInt>(C(i)));
208 }
209
210 Value *Builder::VIMMED1(uint32_t i)
211 {
212 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
213 }
214
215 Value *Builder::VIMMED1_16(uint32_t i)
216 {
217 return ConstantVector::getSplat(mVWidth16, cast<ConstantInt>(C(i)));
218 }
219
220 Value *Builder::VIMMED1(float i)
221 {
222 return ConstantVector::getSplat(mVWidth, cast<ConstantFP>(C(i)));
223 }
224
225 Value *Builder::VIMMED1_16(float i)
226 {
227 return ConstantVector::getSplat(mVWidth16, cast<ConstantFP>(C(i)));
228 }
229
230 Value *Builder::VIMMED1(bool i)
231 {
232 return ConstantVector::getSplat(mVWidth, cast<ConstantInt>(C(i)));
233 }
234
235 Value *Builder::VIMMED1_16(bool i)
236 {
237 return ConstantVector::getSplat(mVWidth16, cast<ConstantInt>(C(i)));
238 }
239
240 Value *Builder::VUNDEF_IPTR()
241 {
242 return UndefValue::get(VectorType::get(mInt32PtrTy,mVWidth));
243 }
244
245 Value *Builder::VUNDEF(Type* t)
246 {
247 return UndefValue::get(VectorType::get(t, mVWidth));
248 }
249
250 Value *Builder::VUNDEF_I()
251 {
252 return UndefValue::get(VectorType::get(mInt32Ty, mVWidth));
253 }
254
255 Value *Builder::VUNDEF_I_16()
256 {
257 return UndefValue::get(VectorType::get(mInt32Ty, mVWidth16));
258 }
259
260 Value *Builder::VUNDEF_F()
261 {
262 return UndefValue::get(VectorType::get(mFP32Ty, mVWidth));
263 }
264
265 Value *Builder::VUNDEF_F_16()
266 {
267 return UndefValue::get(VectorType::get(mFP32Ty, mVWidth16));
268 }
269
270 Value *Builder::VUNDEF(Type *ty, uint32_t size)
271 {
272 return UndefValue::get(VectorType::get(ty, size));
273 }
274
275 Value *Builder::VBROADCAST(Value *src, const llvm::Twine& name)
276 {
277 // check if src is already a vector
278 if (src->getType()->isVectorTy())
279 {
280 return src;
281 }
282
283 return VECTOR_SPLAT(mVWidth, src, name);
284 }
285
286 Value *Builder::VBROADCAST_16(Value *src)
287 {
288 // check if src is already a vector
289 if (src->getType()->isVectorTy())
290 {
291 return src;
292 }
293
294 return VECTOR_SPLAT(mVWidth16, src);
295 }
296
297 uint32_t Builder::IMMED(Value* v)
298 {
299 SWR_ASSERT(isa<ConstantInt>(v));
300 ConstantInt *pValConst = cast<ConstantInt>(v);
301 return pValConst->getZExtValue();
302 }
303
304 int32_t Builder::S_IMMED(Value* v)
305 {
306 SWR_ASSERT(isa<ConstantInt>(v));
307 ConstantInt *pValConst = cast<ConstantInt>(v);
308 return pValConst->getSExtValue();
309 }
310
311 CallInst *Builder::CALL(Value *Callee, const std::initializer_list<Value*> &argsList, const llvm::Twine& name)
312 {
313 std::vector<Value*> args;
314 for (auto arg : argsList)
315 args.push_back(arg);
316 return CALLA(Callee, args, name);
317 }
318
319 CallInst *Builder::CALL(Value *Callee, Value* arg)
320 {
321 std::vector<Value*> args;
322 args.push_back(arg);
323 return CALLA(Callee, args);
324 }
325
326 CallInst *Builder::CALL2(Value *Callee, Value* arg1, Value* arg2)
327 {
328 std::vector<Value*> args;
329 args.push_back(arg1);
330 args.push_back(arg2);
331 return CALLA(Callee, args);
332 }
333
334 CallInst *Builder::CALL3(Value *Callee, Value* arg1, Value* arg2, Value* arg3)
335 {
336 std::vector<Value*> args;
337 args.push_back(arg1);
338 args.push_back(arg2);
339 args.push_back(arg3);
340 return CALLA(Callee, args);
341 }
342
343 Value *Builder::VRCP(Value *va, const llvm::Twine& name)
344 {
345 return FDIV(VIMMED1(1.0f), va, name); // 1 / a
346 }
347
348 Value *Builder::VPLANEPS(Value* vA, Value* vB, Value* vC, Value* &vX, Value* &vY)
349 {
350 Value* vOut = FMADDPS(vA, vX, vC);
351 vOut = FMADDPS(vB, vY, vOut);
352 return vOut;
353 }
354
355 //////////////////////////////////////////////////////////////////////////
356 /// @brief insert a JIT call to CallPrint
357 /// - outputs formatted string to both stdout and VS output window
358 /// - DEBUG builds only
359 /// Usage example:
360 /// PRINT("index %d = 0x%p\n",{C(lane), pIndex});
361 /// where C(lane) creates a constant value to print, and pIndex is the Value*
362 /// result from a GEP, printing out the pointer to memory
363 /// @param printStr - constant string to print, which includes format specifiers
364 /// @param printArgs - initializer list of Value*'s to print to std out
365 CallInst *Builder::PRINT(const std::string &printStr,const std::initializer_list<Value*> &printArgs)
366 {
367 // push the arguments to CallPrint into a vector
368 std::vector<Value*> printCallArgs;
369 // save room for the format string. we still need to modify it for vectors
370 printCallArgs.resize(1);
371
372 // search through the format string for special processing
373 size_t pos = 0;
374 std::string tempStr(printStr);
375 pos = tempStr.find('%', pos);
376 auto v = printArgs.begin();
377
378 while ((pos != std::string::npos) && (v != printArgs.end()))
379 {
380 Value* pArg = *v;
381 Type* pType = pArg->getType();
382
383 if (pType->isVectorTy())
384 {
385 Type* pContainedType = pType->getContainedType(0);
386
387 if (toupper(tempStr[pos + 1]) == 'X')
388 {
389 tempStr[pos] = '0';
390 tempStr[pos + 1] = 'x';
391 tempStr.insert(pos + 2, "%08X ");
392 pos += 7;
393
394 printCallArgs.push_back(VEXTRACT(pArg, C(0)));
395
396 std::string vectorFormatStr;
397 for (uint32_t i = 1; i < pType->getVectorNumElements(); ++i)
398 {
399 vectorFormatStr += "0x%08X ";
400 printCallArgs.push_back(VEXTRACT(pArg, C(i)));
401 }
402
403 tempStr.insert(pos, vectorFormatStr);
404 pos += vectorFormatStr.size();
405 }
406 else if ((tempStr[pos + 1] == 'f') && (pContainedType->isFloatTy()))
407 {
408 uint32_t i = 0;
409 for (; i < (pArg->getType()->getVectorNumElements()) - 1; i++)
410 {
411 tempStr.insert(pos, std::string("%f "));
412 pos += 3;
413 printCallArgs.push_back(FP_EXT(VEXTRACT(pArg, C(i)), Type::getDoubleTy(JM()->mContext)));
414 }
415 printCallArgs.push_back(FP_EXT(VEXTRACT(pArg, C(i)), Type::getDoubleTy(JM()->mContext)));
416 }
417 else if ((tempStr[pos + 1] == 'd') && (pContainedType->isIntegerTy()))
418 {
419 uint32_t i = 0;
420 for (; i < (pArg->getType()->getVectorNumElements()) - 1; i++)
421 {
422 tempStr.insert(pos, std::string("%d "));
423 pos += 3;
424 printCallArgs.push_back(S_EXT(VEXTRACT(pArg, C(i)), Type::getInt32Ty(JM()->mContext)));
425 }
426 printCallArgs.push_back(S_EXT(VEXTRACT(pArg, C(i)), Type::getInt32Ty(JM()->mContext)));
427 }
428 else if ((tempStr[pos + 1] == 'u') && (pContainedType->isIntegerTy()))
429 {
430 uint32_t i = 0;
431 for (; i < (pArg->getType()->getVectorNumElements()) - 1; i++)
432 {
433 tempStr.insert(pos, std::string("%d "));
434 pos += 3;
435 printCallArgs.push_back(Z_EXT(VEXTRACT(pArg, C(i)), Type::getInt32Ty(JM()->mContext)));
436 }
437 printCallArgs.push_back(Z_EXT(VEXTRACT(pArg, C(i)), Type::getInt32Ty(JM()->mContext)));
438 }
439 }
440 else
441 {
442 if (toupper(tempStr[pos + 1]) == 'X')
443 {
444 tempStr[pos] = '0';
445 tempStr.insert(pos + 1, "x%08");
446 printCallArgs.push_back(pArg);
447 pos += 3;
448 }
449 // for %f we need to cast float Values to doubles so that they print out correctly
450 else if ((tempStr[pos + 1] == 'f') && (pType->isFloatTy()))
451 {
452 printCallArgs.push_back(FP_EXT(pArg, Type::getDoubleTy(JM()->mContext)));
453 pos++;
454 }
455 else
456 {
457 printCallArgs.push_back(pArg);
458 }
459 }
460
461 // advance to the next arguement
462 v++;
463 pos = tempStr.find('%', ++pos);
464 }
465
466 // create global variable constant string
467 Constant *constString = ConstantDataArray::getString(JM()->mContext,tempStr,true);
468 GlobalVariable *gvPtr = new GlobalVariable(constString->getType(),true,GlobalValue::InternalLinkage,constString,"printStr");
469 JM()->mpCurrentModule->getGlobalList().push_back(gvPtr);
470
471 // get a pointer to the first character in the constant string array
472 std::vector<Constant*> geplist{C(0),C(0)};
473 Constant *strGEP = ConstantExpr::getGetElementPtr(nullptr, gvPtr,geplist,false);
474
475 // insert the pointer to the format string in the argument vector
476 printCallArgs[0] = strGEP;
477
478 // get pointer to CallPrint function and insert decl into the module if needed
479 std::vector<Type*> args;
480 args.push_back(PointerType::get(mInt8Ty,0));
481 FunctionType* callPrintTy = FunctionType::get(Type::getVoidTy(JM()->mContext),args,true);
482 Function *callPrintFn = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("CallPrint", callPrintTy));
483
484 // if we haven't yet added the symbol to the symbol table
485 if((sys::DynamicLibrary::SearchForAddressOfSymbol("CallPrint")) == nullptr)
486 {
487 sys::DynamicLibrary::AddSymbol("CallPrint", (void *)&CallPrint);
488 }
489
490 // insert a call to CallPrint
491 return CALLA(callPrintFn,printCallArgs);
492 }
493
494 //////////////////////////////////////////////////////////////////////////
495 /// @brief Wrapper around PRINT with initializer list.
496 CallInst* Builder::PRINT(const std::string &printStr)
497 {
498 return PRINT(printStr, {});
499 }
500
501 Value *Builder::EXTRACT_16(Value *x, uint32_t imm)
502 {
503 if (imm == 0)
504 {
505 return VSHUFFLE(x, UndefValue::get(x->getType()), { 0, 1, 2, 3, 4, 5, 6, 7 });
506 }
507 else
508 {
509 return VSHUFFLE(x, UndefValue::get(x->getType()), { 8, 9, 10, 11, 12, 13, 14, 15 });
510 }
511 }
512
513 Value *Builder::JOIN_16(Value *a, Value *b)
514 {
515 return VSHUFFLE(a, b, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });
516 }
517
518 //////////////////////////////////////////////////////////////////////////
519 /// @brief convert x86 <N x float> mask to llvm <N x i1> mask
520 Value *Builder::MASK(Value *vmask)
521 {
522 Value *src = BITCAST(vmask, mSimdInt32Ty);
523 return ICMP_SLT(src, VIMMED1(0));
524 }
525
526 Value *Builder::MASK_16(Value *vmask)
527 {
528 Value *src = BITCAST(vmask, mSimd16Int32Ty);
529 return ICMP_SLT(src, VIMMED1_16(0));
530 }
531
532 //////////////////////////////////////////////////////////////////////////
533 /// @brief convert llvm <N x i1> mask to x86 <N x i32> mask
534 Value *Builder::VMASK(Value *mask)
535 {
536 return S_EXT(mask, mSimdInt32Ty);
537 }
538
539 Value *Builder::VMASK_16(Value *mask)
540 {
541 return S_EXT(mask, mSimd16Int32Ty);
542 }
543
544 /// @brief Convert <Nxi1> llvm mask to integer
545 Value *Builder::VMOVMSK(Value* mask)
546 {
547 SWR_ASSERT(mask->getType()->getVectorElementType() == mInt1Ty);
548 uint32_t numLanes = mask->getType()->getVectorNumElements();
549 Value* i32Result;
550 if (numLanes == 8)
551 {
552 i32Result = BITCAST(mask, mInt8Ty);
553 }
554 else if (numLanes == 16)
555 {
556 i32Result = BITCAST(mask, mInt16Ty);
557 }
558 else
559 {
560 SWR_ASSERT("Unsupported vector width");
561 i32Result = BITCAST(mask, mInt8Ty);
562 }
563 return Z_EXT(i32Result, mInt32Ty);
564 }
565
566 //////////////////////////////////////////////////////////////////////////
567 /// @brief Generate a VPSHUFB operation in LLVM IR. If not
568 /// supported on the underlying platform, emulate it
569 /// @param a - 256bit SIMD(32x8bit) of 8bit integer values
570 /// @param b - 256bit SIMD(32x8bit) of 8bit integer mask values
571 /// Byte masks in lower 128 lane of b selects 8 bit values from lower
572 /// 128bits of a, and vice versa for the upper lanes. If the mask
573 /// value is negative, '0' is inserted.
574 Value *Builder::PSHUFB(Value* a, Value* b)
575 {
576 Value* res;
577 // use avx2 pshufb instruction if available
578 if(JM()->mArch.AVX2())
579 {
580 res = VPSHUFB(a, b);
581 }
582 else
583 {
584 Constant* cB = dyn_cast<Constant>(b);
585 // number of 8 bit elements in b
586 uint32_t numElms = cast<VectorType>(cB->getType())->getNumElements();
587 // output vector
588 Value* vShuf = UndefValue::get(VectorType::get(mInt8Ty, numElms));
589
590 // insert an 8 bit value from the high and low lanes of a per loop iteration
591 numElms /= 2;
592 for(uint32_t i = 0; i < numElms; i++)
593 {
594 ConstantInt* cLow128b = cast<ConstantInt>(cB->getAggregateElement(i));
595 ConstantInt* cHigh128b = cast<ConstantInt>(cB->getAggregateElement(i + numElms));
596
597 // extract values from constant mask
598 char valLow128bLane = (char)(cLow128b->getSExtValue());
599 char valHigh128bLane = (char)(cHigh128b->getSExtValue());
600
601 Value* insertValLow128b;
602 Value* insertValHigh128b;
603
604 // if the mask value is negative, insert a '0' in the respective output position
605 // otherwise, lookup the value at mask position (bits 3..0 of the respective mask byte) in a and insert in output vector
606 insertValLow128b = (valLow128bLane < 0) ? C((char)0) : VEXTRACT(a, C((valLow128bLane & 0xF)));
607 insertValHigh128b = (valHigh128bLane < 0) ? C((char)0) : VEXTRACT(a, C((valHigh128bLane & 0xF) + numElms));
608
609 vShuf = VINSERT(vShuf, insertValLow128b, i);
610 vShuf = VINSERT(vShuf, insertValHigh128b, (i + numElms));
611 }
612 res = vShuf;
613 }
614 return res;
615 }
616
617 //////////////////////////////////////////////////////////////////////////
618 /// @brief Generate a VPSHUFB operation (sign extend 8 8bit values to 32
619 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
620 /// @param a - 128bit SIMD lane(16x8bit) of 8bit integer values. Only
621 /// lower 8 values are used.
622 Value *Builder::PMOVSXBD(Value* a)
623 {
624 // VPMOVSXBD output type
625 Type* v8x32Ty = VectorType::get(mInt32Ty, 8);
626 // Extract 8 values from 128bit lane and sign extend
627 return S_EXT(VSHUFFLE(a, a, C<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty);
628 }
629
630 //////////////////////////////////////////////////////////////////////////
631 /// @brief Generate a VPSHUFB operation (sign extend 8 16bit values to 32
632 /// bits)in LLVM IR. If not supported on the underlying platform, emulate it
633 /// @param a - 128bit SIMD lane(8x16bit) of 16bit integer values.
634 Value *Builder::PMOVSXWD(Value* a)
635 {
636 // VPMOVSXWD output type
637 Type* v8x32Ty = VectorType::get(mInt32Ty, 8);
638 // Extract 8 values from 128bit lane and sign extend
639 return S_EXT(VSHUFFLE(a, a, C<int>({0, 1, 2, 3, 4, 5, 6, 7})), v8x32Ty);
640 }
641
642 //////////////////////////////////////////////////////////////////////////
643 /// @brief Generate a VCVTPH2PS operation (float16->float32 conversion)
644 /// in LLVM IR. If not supported on the underlying platform, emulate it
645 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
646 Value *Builder::CVTPH2PS(Value* a, const llvm::Twine& name)
647 {
648 if (JM()->mArch.F16C())
649 {
650 return VCVTPH2PS(a, name);
651 }
652 else
653 {
654 FunctionType* pFuncTy = FunctionType::get(mFP32Ty, mInt16Ty);
655 Function* pCvtPh2Ps = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("ConvertFloat16ToFloat32", pFuncTy));
656
657 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertFloat16ToFloat32") == nullptr)
658 {
659 sys::DynamicLibrary::AddSymbol("ConvertFloat16ToFloat32", (void *)&ConvertFloat16ToFloat32);
660 }
661
662 Value* pResult = UndefValue::get(mSimdFP32Ty);
663 for (uint32_t i = 0; i < mVWidth; ++i)
664 {
665 Value* pSrc = VEXTRACT(a, C(i));
666 Value* pConv = CALL(pCvtPh2Ps, std::initializer_list<Value*>{pSrc});
667 pResult = VINSERT(pResult, pConv, C(i));
668 }
669
670 pResult->setName(name);
671 return pResult;
672 }
673 }
674
675 //////////////////////////////////////////////////////////////////////////
676 /// @brief Generate a VCVTPS2PH operation (float32->float16 conversion)
677 /// in LLVM IR. If not supported on the underlying platform, emulate it
678 /// @param a - 128bit SIMD lane(8x16bit) of float16 in int16 format.
679 Value *Builder::CVTPS2PH(Value* a, Value* rounding)
680 {
681 if (JM()->mArch.F16C())
682 {
683 return VCVTPS2PH(a, rounding);
684 }
685 else
686 {
687 // call scalar C function for now
688 FunctionType* pFuncTy = FunctionType::get(mInt16Ty, mFP32Ty);
689 Function* pCvtPs2Ph = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("ConvertFloat32ToFloat16", pFuncTy));
690
691 if (sys::DynamicLibrary::SearchForAddressOfSymbol("ConvertFloat32ToFloat16") == nullptr)
692 {
693 sys::DynamicLibrary::AddSymbol("ConvertFloat32ToFloat16", (void *)&ConvertFloat32ToFloat16);
694 }
695
696 Value* pResult = UndefValue::get(mSimdInt16Ty);
697 for (uint32_t i = 0; i < mVWidth; ++i)
698 {
699 Value* pSrc = VEXTRACT(a, C(i));
700 Value* pConv = CALL(pCvtPs2Ph, std::initializer_list<Value*>{pSrc});
701 pResult = VINSERT(pResult, pConv, C(i));
702 }
703
704 return pResult;
705 }
706 }
707
708 Value *Builder::PMAXSD(Value* a, Value* b)
709 {
710 Value* cmp = ICMP_SGT(a, b);
711 return SELECT(cmp, a, b);
712 }
713
714 Value *Builder::PMINSD(Value* a, Value* b)
715 {
716 Value* cmp = ICMP_SLT(a, b);
717 return SELECT(cmp, a, b);
718 }
719
720 Value *Builder::PMAXUD(Value* a, Value* b)
721 {
722 Value* cmp = ICMP_UGT(a, b);
723 return SELECT(cmp, a, b);
724 }
725
726 Value *Builder::PMINUD(Value* a, Value* b)
727 {
728 Value* cmp = ICMP_ULT(a, b);
729 return SELECT(cmp, a, b);
730 }
731
732 // Helper function to create alloca in entry block of function
733 Value* Builder::CreateEntryAlloca(Function* pFunc, Type* pType)
734 {
735 auto saveIP = IRB()->saveIP();
736 IRB()->SetInsertPoint(&pFunc->getEntryBlock(),
737 pFunc->getEntryBlock().begin());
738 Value* pAlloca = ALLOCA(pType);
739 if (saveIP.isSet()) IRB()->restoreIP(saveIP);
740 return pAlloca;
741 }
742
743 Value* Builder::CreateEntryAlloca(Function* pFunc, Type* pType, Value* pArraySize)
744 {
745 auto saveIP = IRB()->saveIP();
746 IRB()->SetInsertPoint(&pFunc->getEntryBlock(),
747 pFunc->getEntryBlock().begin());
748 Value* pAlloca = ALLOCA(pType, pArraySize);
749 if (saveIP.isSet()) IRB()->restoreIP(saveIP);
750 return pAlloca;
751 }
752
753 Value* Builder::VABSPS(Value* a)
754 {
755 Value* asInt = BITCAST(a, mSimdInt32Ty);
756 Value* result = BITCAST(AND(asInt, VIMMED1(0x7fffffff)), mSimdFP32Ty);
757 return result;
758 }
759
760 Value *Builder::ICLAMP(Value* src, Value* low, Value* high, const llvm::Twine& name)
761 {
762 Value *lowCmp = ICMP_SLT(src, low);
763 Value *ret = SELECT(lowCmp, low, src);
764
765 Value *highCmp = ICMP_SGT(ret, high);
766 ret = SELECT(highCmp, high, ret, name);
767
768 return ret;
769 }
770
771 Value *Builder::FCLAMP(Value* src, Value* low, Value* high)
772 {
773 Value *lowCmp = FCMP_OLT(src, low);
774 Value *ret = SELECT(lowCmp, low, src);
775
776 Value *highCmp = FCMP_OGT(ret, high);
777 ret = SELECT(highCmp, high, ret);
778
779 return ret;
780 }
781
782 Value *Builder::FCLAMP(Value* src, float low, float high)
783 {
784 Value* result = VMAXPS(src, VIMMED1(low));
785 result = VMINPS(result, VIMMED1(high));
786
787 return result;
788 }
789
790 Value *Builder::FMADDPS(Value* a, Value* b, Value* c)
791 {
792 Value* vOut;
793 // use FMADs if available
794 if(JM()->mArch.AVX2())
795 {
796 vOut = VFMADDPS(a, b, c);
797 }
798 else
799 {
800 vOut = FADD(FMUL(a, b), c);
801 }
802 return vOut;
803 }
804
805 //////////////////////////////////////////////////////////////////////////
806 /// @brief pop count on vector mask (e.g. <8 x i1>)
807 Value* Builder::VPOPCNT(Value* a)
808 {
809 return POPCNT(VMOVMSK(a));
810 }
811
812 //////////////////////////////////////////////////////////////////////////
813 /// @brief C functions called by LLVM IR
814 //////////////////////////////////////////////////////////////////////////
815
816 Value *Builder::VEXTRACTI128(Value* a, Constant* imm8)
817 {
818 bool flag = !imm8->isZeroValue();
819 SmallVector<Constant*,8> idx;
820 for (unsigned i = 0; i < mVWidth / 2; i++) {
821 idx.push_back(C(flag ? i + mVWidth / 2 : i));
822 }
823 return VSHUFFLE(a, VUNDEF_I(), ConstantVector::get(idx));
824 }
825
826 Value *Builder::VINSERTI128(Value* a, Value* b, Constant* imm8)
827 {
828 bool flag = !imm8->isZeroValue();
829 SmallVector<Constant*,8> idx;
830 for (unsigned i = 0; i < mVWidth; i++) {
831 idx.push_back(C(i));
832 }
833 Value *inter = VSHUFFLE(b, VUNDEF_I(), ConstantVector::get(idx));
834
835 SmallVector<Constant*,8> idx2;
836 for (unsigned i = 0; i < mVWidth / 2; i++) {
837 idx2.push_back(C(flag ? i : i + mVWidth));
838 }
839 for (unsigned i = mVWidth / 2; i < mVWidth; i++) {
840 idx2.push_back(C(flag ? i + mVWidth / 2 : i));
841 }
842 return VSHUFFLE(a, inter, ConstantVector::get(idx2));
843 }
844
845 // rdtsc buckets macros
846 void Builder::RDTSC_START(Value* pBucketMgr, Value* pId)
847 {
848 // @todo due to an issue with thread local storage propagation in llvm, we can only safely call into
849 // buckets framework when single threaded
850 if (KNOB_SINGLE_THREADED)
851 {
852 std::vector<Type*> args{
853 PointerType::get(mInt32Ty, 0), // pBucketMgr
854 mInt32Ty // id
855 };
856
857 FunctionType* pFuncTy = FunctionType::get(Type::getVoidTy(JM()->mContext), args, false);
858 Function* pFunc = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("BucketManager_StartBucket", pFuncTy));
859 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StartBucket") == nullptr)
860 {
861 sys::DynamicLibrary::AddSymbol("BucketManager_StartBucket", (void*)&BucketManager_StartBucket);
862 }
863
864 CALL(pFunc, { pBucketMgr, pId });
865 }
866 }
867
868 void Builder::RDTSC_STOP(Value* pBucketMgr, Value* pId)
869 {
870 // @todo due to an issue with thread local storage propagation in llvm, we can only safely call into
871 // buckets framework when single threaded
872 if (KNOB_SINGLE_THREADED)
873 {
874 std::vector<Type*> args{
875 PointerType::get(mInt32Ty, 0), // pBucketMgr
876 mInt32Ty // id
877 };
878
879 FunctionType* pFuncTy = FunctionType::get(Type::getVoidTy(JM()->mContext), args, false);
880 Function* pFunc = cast<Function>(JM()->mpCurrentModule->getOrInsertFunction("BucketManager_StopBucket", pFuncTy));
881 if (sys::DynamicLibrary::SearchForAddressOfSymbol("BucketManager_StopBucket") == nullptr)
882 {
883 sys::DynamicLibrary::AddSymbol("BucketManager_StopBucket", (void*)&BucketManager_StopBucket);
884 }
885
886 CALL(pFunc, { pBucketMgr, pId });
887 }
888 }
889
890 uint32_t Builder::GetTypeSize(Type* pType)
891 {
892 if (pType->isStructTy())
893 {
894 uint32_t numElems = pType->getStructNumElements();
895 Type* pElemTy = pType->getStructElementType(0);
896 return numElems * GetTypeSize(pElemTy);
897 }
898
899 if (pType->isArrayTy())
900 {
901 uint32_t numElems = pType->getArrayNumElements();
902 Type* pElemTy = pType->getArrayElementType();
903 return numElems * GetTypeSize(pElemTy);
904 }
905
906 if (pType->isIntegerTy())
907 {
908 uint32_t bitSize = pType->getIntegerBitWidth();
909 return bitSize / 8;
910 }
911
912 if (pType->isFloatTy())
913 {
914 return 4;
915 }
916
917 if (pType->isHalfTy())
918 {
919 return 2;
920 }
921
922 if (pType->isDoubleTy())
923 {
924 return 8;
925 }
926
927 SWR_ASSERT(false, "Unimplemented type.");
928 return 0;
929 }
930 }