| 1 |
//===- SPIRVUtil.cpp - SPIR-V Utilities -------------------------*- C++ -*-===// |
| 2 |
// |
| 3 |
// The LLVM/SPIRV Translator |
| 4 |
// |
| 5 |
// This file is distributed under the University of Illinois Open Source |
| 6 |
// License. See LICENSE.TXT for details. |
| 7 |
// |
| 8 |
// Copyright (c) 2014 Advanced Micro Devices, Inc. All rights reserved. |
| 9 |
// |
| 10 |
// Permission is hereby granted, free of charge, to any person obtaining a |
| 11 |
// copy of this software and associated documentation files (the "Software"), |
| 12 |
// to deal with the Software without restriction, including without limitation |
| 13 |
// the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 14 |
// and/or sell copies of the Software, and to permit persons to whom the |
| 15 |
// Software is furnished to do so, subject to the following conditions: |
| 16 |
// |
| 17 |
// Redistributions of source code must retain the above copyright notice, |
| 18 |
// this list of conditions and the following disclaimers. |
| 19 |
// Redistributions in binary form must reproduce the above copyright notice, |
| 20 |
// this list of conditions and the following disclaimers in the documentation |
| 21 |
// and/or other materials provided with the distribution. |
| 22 |
// Neither the names of Advanced Micro Devices, Inc., nor the names of its |
| 23 |
// contributors may be used to endorse or promote products derived from this |
| 24 |
// Software without specific prior written permission. |
| 25 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 26 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 27 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 28 |
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 29 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 30 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH |
| 31 |
// THE SOFTWARE. |
| 32 |
// |
| 33 |
//===----------------------------------------------------------------------===// |
| 34 |
/// \file |
| 35 |
/// |
| 36 |
/// This file defines utility classes and functions shared by SPIR-V |
| 37 |
/// reader/writer. |
| 38 |
/// |
| 39 |
//===----------------------------------------------------------------------===// |
| 40 |
|
| 41 |
// This file needs to be included before anything that declares |
| 42 |
// llvm::PointerType to avoid a compilation bug on MSVC. |
| 43 |
#include "llvm/Demangle/Demangle.h" |
| 44 |
#include "llvm/Demangle/ItaniumDemangle.h" |
| 45 |
|
| 46 |
#include "FunctionDescriptor.h" |
| 47 |
#include "ManglingUtils.h" |
| 48 |
#include "NameMangleAPI.h" |
| 49 |
#include "OCLUtil.h" |
| 50 |
#include "ParameterType.h" |
| 51 |
#include "SPIRVInternal.h" |
| 52 |
#include "SPIRVMDWalker.h" |
| 53 |
#include "libSPIRV/SPIRVDecorate.h" |
| 54 |
#include "libSPIRV/SPIRVValue.h" |
| 55 |
|
| 56 |
#include "llvm/ADT/StringSwitch.h" |
| 57 |
#include "llvm/Bitcode/BitcodeWriter.h" |
| 58 |
#include "llvm/IR/IRBuilder.h" |
| 59 |
#include "llvm/IR/IntrinsicInst.h" |
| 60 |
#include "llvm/IR/Metadata.h" |
| 61 |
#include "llvm/IR/TypedPointerType.h" |
| 62 |
#include "llvm/Support/CommandLine.h" |
| 63 |
#include "llvm/Support/Debug.h" |
| 64 |
#include "llvm/Support/ErrorHandling.h" |
| 65 |
#include "llvm/Support/FileSystem.h" |
| 66 |
#include "llvm/Support/ToolOutputFile.h" |
| 67 |
|
| 68 |
#include <functional> |
| 69 |
#include <sstream> |
| 70 |
|
| 71 |
#define DEBUG_TYPE "spirv" |
| 72 |
|
| 73 |
namespace SPIRV { |
| 74 |
|
| 75 |
#ifdef _SPIRV_SUPPORT_TEXT_FMT |
| 76 |
cl::opt<bool, true> |
| 77 |
UseTextFormat("spirv-text", |
| 78 |
cl::desc("Use text format for SPIR-V for debugging purpose"), |
| 79 |
cl::location(SPIRVUseTextFormat)); |
| 80 |
#endif |
| 81 |
|
| 82 |
#ifdef _SPIRVDBG |
| 83 |
cl::opt<bool, true> EnableDbgOutput("spirv-debug", |
| 84 |
cl::desc("Enable SPIR-V debug output"), |
| 85 |
cl::location(SPIRVDbgEnable)); |
| 86 |
#endif |
| 87 |
|
| 88 |
bool isSupportedTriple(Triple T) { return T.isSPIR() || T.isSPIRV(); } |
| 89 |
|
| 90 |
void addFnAttr(CallInst *Call, Attribute::AttrKind Attr) { |
| 91 |
Call->addFnAttr(Attr); |
| 92 |
} |
| 93 |
|
| 94 |
void removeFnAttr(CallInst *Call, Attribute::AttrKind Attr) { |
| 95 |
Call->removeFnAttr(Attr); |
| 96 |
} |
| 97 |
|
| 98 |
Value *extendVector(Value *V, FixedVectorType *NewType, |
| 99 |
IRBuilderBase &Builder) { |
| 100 |
unsigned OldSize = cast<FixedVectorType>(V->getType())->getNumElements(); |
| 101 |
unsigned NewSize = NewType->getNumElements(); |
| 102 |
assert(OldSize < NewSize); |
| 103 |
std::vector<Constant *> Components; |
| 104 |
IntegerType *Int32Ty = Builder.getInt32Ty(); |
| 105 |
for (unsigned I = 0; I < NewSize; I++) { |
| 106 |
if (I < OldSize) |
| 107 |
Components.push_back(ConstantInt::get(Int32Ty, I)); |
| 108 |
else |
| 109 |
Components.push_back(PoisonValue::get(Int32Ty)); |
| 110 |
} |
| 111 |
|
| 112 |
return Builder.CreateShuffleVector(V, PoisonValue::get(V->getType()), |
| 113 |
ConstantVector::get(Components), "vecext"); |
| 114 |
} |
| 115 |
|
| 116 |
void saveLLVMModule(Module *M, const std::string &OutputFile) { |
| 117 |
std::error_code EC; |
| 118 |
ToolOutputFile Out(OutputFile.c_str(), EC, sys::fs::OF_None); |
| 119 |
if (EC) { |
| 120 |
SPIRVDBG(errs() << "Fails to open output file: " << EC.message();) |
| 121 |
return; |
| 122 |
} |
| 123 |
|
| 124 |
WriteBitcodeToFile(*M, Out.os()); |
| 125 |
Out.keep(); |
| 126 |
} |
| 127 |
|
| 128 |
std::string mapLLVMTypeToOCLType(const Type *Ty, bool Signed, Type *PET) { |
| 129 |
if (Ty->isHalfTy()) |
| 130 |
return "half"; |
| 131 |
if (Ty->isFloatTy()) |
| 132 |
return "float"; |
| 133 |
if (Ty->isDoubleTy()) |
| 134 |
return "double"; |
| 135 |
if (auto IntTy = dyn_cast<IntegerType>(Ty)) { |
| 136 |
std::string SignPrefix; |
| 137 |
std::string Stem; |
| 138 |
if (!Signed) |
| 139 |
SignPrefix = "u"; |
| 140 |
switch (IntTy->getIntegerBitWidth()) { |
| 141 |
case 8: |
| 142 |
Stem = "char"; |
| 143 |
break; |
| 144 |
case 16: |
| 145 |
Stem = "short"; |
| 146 |
break; |
| 147 |
case 32: |
| 148 |
Stem = "int"; |
| 149 |
break; |
| 150 |
case 64: |
| 151 |
Stem = "long"; |
| 152 |
break; |
| 153 |
default: |
| 154 |
Stem = "invalid_type"; |
| 155 |
break; |
| 156 |
} |
| 157 |
return SignPrefix + Stem; |
| 158 |
} |
| 159 |
if (auto VecTy = dyn_cast<FixedVectorType>(Ty)) { |
| 160 |
Type *EleTy = VecTy->getElementType(); |
| 161 |
unsigned Size = VecTy->getNumElements(); |
| 162 |
std::stringstream Ss; |
| 163 |
Ss << mapLLVMTypeToOCLType(EleTy, Signed) << Size; |
| 164 |
return Ss.str(); |
| 165 |
} |
| 166 |
// It is expected that `Ty` can be mapped to `ReturnType` from "Optional |
| 167 |
// Postfixes for SPIR-V Builtin Function Names" section of |
| 168 |
// SPIRVRepresentationInLLVM.rst document (aka SPIRV-friendly IR). |
| 169 |
// If `Ty` is not a scalar or vector type mentioned in the document (return |
| 170 |
// value of some SPIR-V instructions may be represented as pointer to a struct |
| 171 |
// in LLVM IR) we can mangle the type. |
| 172 |
BuiltinFuncMangleInfo MangleInfo; |
| 173 |
if (Ty->isPointerTy()) { |
| 174 |
assert(cast<PointerType>(const_cast<Type *>(Ty)) |
| 175 |
->isOpaqueOrPointeeTypeMatches(PET)); |
| 176 |
Ty = TypedPointerType::get(PET, Ty->getPointerAddressSpace()); |
| 177 |
} |
| 178 |
std::string MangledName = |
| 179 |
mangleBuiltin("", const_cast<Type *>(Ty), &MangleInfo); |
| 180 |
// Remove "_Z0"(3 characters) from the front of the name |
| 181 |
return MangledName.erase(0, 3); |
| 182 |
} |
| 183 |
|
| 184 |
StructType *getOrCreateOpaqueStructType(Module *M, StringRef Name) { |
| 185 |
auto OpaqueType = StructType::getTypeByName(M->getContext(), Name); |
| 186 |
if (!OpaqueType) |
| 187 |
OpaqueType = StructType::create(M->getContext(), Name); |
| 188 |
return OpaqueType; |
| 189 |
} |
| 190 |
|
| 191 |
void getFunctionTypeParameterTypes(llvm::FunctionType *FT, |
| 192 |
SmallVector<Type *> &ArgTys) { |
| 193 |
for (auto I = FT->param_begin(), E = FT->param_end(); I != E; ++I) { |
| 194 |
ArgTys.push_back(*I); |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
bool isVoidFuncTy(FunctionType *FT) { return FT->getReturnType()->isVoidTy(); } |
| 199 |
|
| 200 |
bool isOCLImageType(llvm::Type *Ty, StringRef *Name) { |
| 201 |
if (auto *TPT = dyn_cast_or_null<TypedPointerType>(Ty)) |
| 202 |
if (auto *ST = dyn_cast_or_null<StructType>(TPT->getElementType())) |
| 203 |
if (ST->isOpaque()) { |
| 204 |
auto FullName = ST->getName(); |
| 205 |
if (FullName.find(kSPR2TypeName::ImagePrefix) == 0) { |
| 206 |
if (Name) |
| 207 |
*Name = FullName.drop_front(strlen(kSPR2TypeName::OCLPrefix)); |
| 208 |
return true; |
| 209 |
} |
| 210 |
} |
| 211 |
if (auto *TET = dyn_cast_or_null<TargetExtType>(Ty)) { |
| 212 |
assert(!Name && "Cannot get the name for a target-extension type image"); |
| 213 |
return TET->getName() == "spirv.Image"; |
| 214 |
} |
| 215 |
return false; |
| 216 |
} |
| 217 |
/// \param BaseTyName is the type Name as in spirv.BaseTyName.Postfixes |
| 218 |
/// \param Postfix contains postfixes extracted from the SPIR-V image |
| 219 |
/// type Name as spirv.BaseTyName.Postfixes. |
| 220 |
bool isSPIRVStructType(llvm::Type *Ty, StringRef BaseTyName, |
| 221 |
StringRef *Postfix) { |
| 222 |
auto *ST = dyn_cast<StructType>(Ty); |
| 223 |
if (!ST) |
| 224 |
return false; |
| 225 |
if (ST->isOpaque()) { |
| 226 |
auto FullName = ST->getName(); |
| 227 |
std::string N = |
| 228 |
std::string(kSPIRVTypeName::PrefixAndDelim) + BaseTyName.str(); |
| 229 |
if (FullName != N) |
| 230 |
N = N + kSPIRVTypeName::Delimiter; |
| 231 |
if (FullName.startswith(N)) { |
| 232 |
if (Postfix) |
| 233 |
*Postfix = FullName.drop_front(N.size()); |
| 234 |
return true; |
| 235 |
} |
| 236 |
} |
| 237 |
return false; |
| 238 |
} |
| 239 |
|
| 240 |
bool isSYCLHalfType(llvm::Type *Ty) { |
| 241 |
if (auto *ST = dyn_cast<StructType>(Ty)) { |
| 242 |
if (!ST->hasName()) |
| 243 |
return false; |
| 244 |
StringRef Name = ST->getName(); |
| 245 |
if (!Name.consume_front("class.")) |
| 246 |
return false; |
| 247 |
if ((Name.startswith("sycl::") || Name.startswith("cl::sycl::") || |
| 248 |
Name.startswith("__sycl_internal::")) && |
| 249 |
Name.endswith("::half")) { |
| 250 |
return true; |
| 251 |
} |
| 252 |
} |
| 253 |
return false; |
| 254 |
} |
| 255 |
|
| 256 |
bool isSYCLBfloat16Type(llvm::Type *Ty) { |
| 257 |
if (auto *ST = dyn_cast<StructType>(Ty)) { |
| 258 |
if (!ST->hasName()) |
| 259 |
return false; |
| 260 |
StringRef Name = ST->getName(); |
| 261 |
if (!Name.consume_front("class.")) |
| 262 |
return false; |
| 263 |
if ((Name.startswith("sycl::") || Name.startswith("cl::sycl::") || |
| 264 |
Name.startswith("__sycl_internal::")) && |
| 265 |
Name.endswith("::bfloat16")) { |
| 266 |
return true; |
| 267 |
} |
| 268 |
} |
| 269 |
return false; |
| 270 |
} |
| 271 |
|
| 272 |
bool isLLVMCooperativeMatrixType(llvm::Type *Ty) { |
| 273 |
if (auto *TargetTy = dyn_cast<TargetExtType>(Ty)) |
| 274 |
return TargetTy->getName() == "spirv.CooperativeMatrixKHR"; |
| 275 |
return false; |
| 276 |
} |
| 277 |
|
| 278 |
Function *getOrCreateFunction(Module *M, Type *RetTy, ArrayRef<Type *> ArgTypes, |
| 279 |
StringRef Name, BuiltinFuncMangleInfo *Mangle, |
| 280 |
AttributeList *Attrs, bool TakeName) { |
| 281 |
std::string MangledName{Name}; |
| 282 |
bool IsVarArg = false; |
| 283 |
if (Mangle) { |
| 284 |
MangledName = mangleBuiltin(Name, ArgTypes, Mangle); |
| 285 |
IsVarArg = 0 <= Mangle->getVarArg(); |
| 286 |
if (IsVarArg) |
| 287 |
ArgTypes = ArgTypes.slice(0, Mangle->getVarArg()); |
| 288 |
} |
| 289 |
FunctionType *FT = FunctionType::get(RetTy, ArgTypes, IsVarArg); |
| 290 |
Function *F = M->getFunction(MangledName); |
| 291 |
if (!TakeName && F && F->getFunctionType() != FT && Mangle != nullptr) { |
| 292 |
std::string S; |
| 293 |
raw_string_ostream SS(S); |
| 294 |
SS << "Error: Attempt to redefine function: " << *F << " => " << *FT |
| 295 |
<< '\n'; |
| 296 |
report_fatal_error(llvm::Twine(SS.str()), false); |
| 297 |
} |
| 298 |
if (!F || F->getFunctionType() != FT) { |
| 299 |
auto NewF = |
| 300 |
Function::Create(FT, GlobalValue::ExternalLinkage, MangledName, M); |
| 301 |
if (F && TakeName) { |
| 302 |
NewF->takeName(F); |
| 303 |
LLVM_DEBUG( |
| 304 |
dbgs() << "[getOrCreateFunction] Warning: taking function Name\n"); |
| 305 |
} |
| 306 |
if (NewF->getName() != MangledName) { |
| 307 |
LLVM_DEBUG( |
| 308 |
dbgs() << "[getOrCreateFunction] Warning: function Name changed\n"); |
| 309 |
} |
| 310 |
LLVM_DEBUG(dbgs() << "[getOrCreateFunction] "; |
| 311 |
if (F) dbgs() << *F << " => "; dbgs() << *NewF << '\n';); |
| 312 |
if (F) |
| 313 |
NewF->setDSOLocal(F->isDSOLocal()); |
| 314 |
F = NewF; |
| 315 |
F->setCallingConv(CallingConv::SPIR_FUNC); |
| 316 |
if (Attrs) |
| 317 |
F->setAttributes(*Attrs); |
| 318 |
} |
| 319 |
return F; |
| 320 |
} |
| 321 |
|
| 322 |
std::vector<Value *> getArguments(CallInst *CI, unsigned Start, unsigned End) { |
| 323 |
std::vector<Value *> Args; |
| 324 |
if (End == 0) |
| 325 |
End = CI->arg_size(); |
| 326 |
for (; Start != End; ++Start) { |
| 327 |
Args.push_back(CI->getArgOperand(Start)); |
| 328 |
} |
| 329 |
return Args; |
| 330 |
} |
| 331 |
|
| 332 |
uint64_t getArgAsInt(CallInst *CI, unsigned I) { |
| 333 |
return cast<ConstantInt>(CI->getArgOperand(I))->getZExtValue(); |
| 334 |
} |
| 335 |
|
| 336 |
Scope getArgAsScope(CallInst *CI, unsigned I) { |
| 337 |
return static_cast<Scope>(getArgAsInt(CI, I)); |
| 338 |
} |
| 339 |
|
| 340 |
Decoration getArgAsDecoration(CallInst *CI, unsigned I) { |
| 341 |
return static_cast<Decoration>(getArgAsInt(CI, I)); |
| 342 |
} |
| 343 |
|
| 344 |
std::string decorateSPIRVFunction(const std::string &S) { |
| 345 |
return std::string(kSPIRVName::Prefix) + S + kSPIRVName::Postfix; |
| 346 |
} |
| 347 |
|
| 348 |
StringRef undecorateSPIRVFunction(StringRef S) { |
| 349 |
assert(S.find(kSPIRVName::Prefix) == 0); |
| 350 |
const size_t Start = strlen(kSPIRVName::Prefix); |
| 351 |
auto End = S.rfind(kSPIRVName::Postfix); |
| 352 |
return S.substr(Start, End - Start); |
| 353 |
} |
| 354 |
|
| 355 |
std::string prefixSPIRVName(const std::string &S) { |
| 356 |
return std::string(kSPIRVName::Prefix) + S; |
| 357 |
} |
| 358 |
|
| 359 |
StringRef dePrefixSPIRVName(StringRef R, SmallVectorImpl<StringRef> &Postfix) { |
| 360 |
const size_t Start = strlen(kSPIRVName::Prefix); |
| 361 |
if (!R.startswith(kSPIRVName::Prefix)) |
| 362 |
return R; |
| 363 |
R = R.drop_front(Start); |
| 364 |
R.split(Postfix, "_", -1, false); |
| 365 |
auto Name = Postfix.front(); |
| 366 |
Postfix.erase(Postfix.begin()); |
| 367 |
return Name; |
| 368 |
} |
| 369 |
|
| 370 |
std::string getSPIRVFuncName(Op OC, StringRef PostFix) { |
| 371 |
return prefixSPIRVName(getName(OC) + PostFix.str()); |
| 372 |
} |
| 373 |
|
| 374 |
std::string getSPIRVFuncName(Op OC, const Type *PRetTy, bool IsSigned, |
| 375 |
Type *PET) { |
| 376 |
return prefixSPIRVName(getName(OC) + kSPIRVPostfix::Divider + |
| 377 |
getPostfixForReturnType(PRetTy, IsSigned, PET)); |
| 378 |
} |
| 379 |
|
| 380 |
std::string getSPIRVFuncName(SPIRVBuiltinVariableKind BVKind) { |
| 381 |
return prefixSPIRVName(getName(BVKind)); |
| 382 |
} |
| 383 |
|
| 384 |
std::string getSPIRVExtFuncName(SPIRVExtInstSetKind Set, unsigned ExtOp, |
| 385 |
StringRef PostFix) { |
| 386 |
std::string ExtOpName; |
| 387 |
switch (Set) { |
| 388 |
default: |
| 389 |
llvm_unreachable("invalid extended instruction set"); |
| 390 |
ExtOpName = "unknown"; |
| 391 |
break; |
| 392 |
case SPIRVEIS_OpenCL: |
| 393 |
ExtOpName = getName(static_cast<OCLExtOpKind>(ExtOp)); |
| 394 |
break; |
| 395 |
} |
| 396 |
return prefixSPIRVName(SPIRVExtSetShortNameMap::map(Set) + '_' + ExtOpName + |
| 397 |
PostFix.str()); |
| 398 |
} |
| 399 |
|
| 400 |
SPIRVDecorate *mapPostfixToDecorate(StringRef Postfix, SPIRVEntry *Target) { |
| 401 |
if (Postfix == kSPIRVPostfix::Sat) |
| 402 |
return new SPIRVDecorate(spv::DecorationSaturatedConversion, Target); |
| 403 |
|
| 404 |
if (Postfix.startswith(kSPIRVPostfix::Rt)) |
| 405 |
return new SPIRVDecorate(spv::DecorationFPRoundingMode, Target, |
| 406 |
map<SPIRVFPRoundingModeKind>(Postfix.str())); |
| 407 |
|
| 408 |
return nullptr; |
| 409 |
} |
| 410 |
|
| 411 |
SPIRVValue *addDecorations(SPIRVValue *Target, |
| 412 |
const SmallVectorImpl<std::string> &Decs) { |
| 413 |
for (auto &I : Decs) |
| 414 |
if (auto Dec = mapPostfixToDecorate(I, Target)) |
| 415 |
Target->addDecorate(Dec); |
| 416 |
return Target; |
| 417 |
} |
| 418 |
|
| 419 |
std::string getPostfix(Decoration Dec, unsigned Value) { |
| 420 |
switch (Dec) { |
| 421 |
default: |
| 422 |
llvm_unreachable("not implemented"); |
| 423 |
return "unknown"; |
| 424 |
case spv::DecorationSaturatedConversion: |
| 425 |
return kSPIRVPostfix::Sat; |
| 426 |
case spv::DecorationFPRoundingMode: |
| 427 |
return rmap<std::string>(static_cast<SPIRVFPRoundingModeKind>(Value)); |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
std::string getPostfixForReturnType(CallInst *CI, bool IsSigned) { |
| 432 |
return getPostfixForReturnType(CI->getType(), IsSigned); |
| 433 |
} |
| 434 |
|
| 435 |
std::string getPostfixForReturnType(const Type *PRetTy, bool IsSigned, |
| 436 |
Type *PET) { |
| 437 |
return std::string(kSPIRVPostfix::Return) + |
| 438 |
mapLLVMTypeToOCLType(PRetTy, IsSigned, PET); |
| 439 |
} |
| 440 |
|
| 441 |
// Enqueue kernel, kernel query, pipe and address space cast built-ins |
| 442 |
// are not mangled. |
| 443 |
bool isNonMangledOCLBuiltin(StringRef Name) { |
| 444 |
if (!Name.startswith("__")) |
| 445 |
return false; |
| 446 |
|
| 447 |
return isEnqueueKernelBI(Name) || isKernelQueryBI(Name) || |
| 448 |
isPipeOrAddressSpaceCastBI(Name.drop_front(2)); |
| 449 |
} |
| 450 |
|
| 451 |
Op getSPIRVFuncOC(StringRef S, SmallVectorImpl<std::string> *Dec) { |
| 452 |
Op OC; |
| 453 |
SmallVector<StringRef, 2> Postfix; |
| 454 |
StringRef Name; |
| 455 |
if (!oclIsBuiltin(S, Name)) |
| 456 |
Name = S; |
| 457 |
StringRef R(Name); |
| 458 |
if ((!Name.startswith(kSPIRVName::Prefix) && !isNonMangledOCLBuiltin(S)) || |
| 459 |
!getByName(dePrefixSPIRVName(R, Postfix).str(), OC)) { |
| 460 |
return OpNop; |
| 461 |
} |
| 462 |
if (Dec) |
| 463 |
for (auto &I : Postfix) |
| 464 |
Dec->push_back(I.str()); |
| 465 |
return OC; |
| 466 |
} |
| 467 |
|
| 468 |
bool getSPIRVBuiltin(const std::string &OrigName, spv::BuiltIn &B) { |
| 469 |
SmallVector<StringRef, 2> Postfix; |
| 470 |
StringRef R(OrigName); |
| 471 |
R = dePrefixSPIRVName(R, Postfix); |
| 472 |
if (!Postfix.empty()) |
| 473 |
return false; |
| 474 |
return getByName(R.str(), B); |
| 475 |
} |
| 476 |
|
| 477 |
// DemangledName is a substring of Name. The DemangledName is updated only |
| 478 |
// if true is returned |
| 479 |
bool oclIsBuiltin(StringRef Name, StringRef &DemangledName, bool IsCpp) { |
| 480 |
if (Name == "printf") { |
| 481 |
DemangledName = Name; |
| 482 |
return true; |
| 483 |
} |
| 484 |
if (isNonMangledOCLBuiltin(Name)) { |
| 485 |
DemangledName = Name.drop_front(2); |
| 486 |
return true; |
| 487 |
} |
| 488 |
if (!Name.startswith("_Z")) |
| 489 |
return false; |
| 490 |
// OpenCL C++ built-ins are declared in cl namespace. |
| 491 |
// TODO: consider using 'St' abbriviation for cl namespace mangling. |
| 492 |
// Similar to ::std:: in C++. |
| 493 |
if (IsCpp) { |
| 494 |
if (!Name.startswith("_ZN")) |
| 495 |
return false; |
| 496 |
// Skip CV and ref qualifiers. |
| 497 |
size_t NameSpaceStart = Name.find_first_not_of("rVKRO", 3); |
| 498 |
// All built-ins are in the ::cl:: namespace. |
| 499 |
if (Name.substr(NameSpaceStart, 11) != "2cl7__spirv") |
| 500 |
return false; |
| 501 |
size_t DemangledNameLenStart = NameSpaceStart + 11; |
| 502 |
size_t Start = Name.find_first_not_of("0123456789", DemangledNameLenStart); |
| 503 |
size_t Len = 0; |
| 504 |
if (Name.substr(DemangledNameLenStart, Start - DemangledNameLenStart) |
| 505 |
.getAsInteger(10, Len)) { |
| 506 |
SPIRVDBG(errs() << "Error in extracting integer value"); |
| 507 |
return false; |
| 508 |
} |
| 509 |
DemangledName = Name.substr(Start, Len); |
| 510 |
} else { |
| 511 |
size_t Start = Name.find_first_not_of("0123456789", 2); |
| 512 |
size_t Len = 0; |
| 513 |
Name.substr(2, Start - 2).getAsInteger(10, Len); |
| 514 |
DemangledName = Name.substr(Start, Len); |
| 515 |
} |
| 516 |
return true; |
| 517 |
} |
| 518 |
|
| 519 |
// DemangledName is a substring of Name. The DemangledName is updated only |
| 520 |
// if true is returned. |
| 521 |
bool isInternalSPIRVBuiltin(StringRef Name, std::string &DemangledName) { |
| 522 |
if (!Name.starts_with("_Z")) |
| 523 |
return false; |
| 524 |
constexpr unsigned DemangledNameLenStart = 2; |
| 525 |
size_t Start = Name.find_first_not_of("0123456789", DemangledNameLenStart); |
| 526 |
if (!Name.substr(Start).starts_with(kSPIRVName::InternalBuiltinPrefix)) |
| 527 |
return false; |
| 528 |
// LLVM 16 doesn't have itaniumDemangle(const char*, bool) overload |
| 529 |
// Try using the C-style API first, but it may fail for types like bfloat (DF16b) |
| 530 |
// that LLVM 16's demangler doesn't recognize |
| 531 |
char *Demangled = llvm::itaniumDemangle(Name.data(), nullptr, nullptr, nullptr); |
| 532 |
|
| 533 |
if (Demangled) { |
| 534 |
// Demangling succeeded - extract function name from demangled string |
| 535 |
std::string FullDemangled(Demangled); |
| 536 |
std::free(Demangled); |
| 537 |
if (!StringRef(FullDemangled).starts_with(kSPIRVName::InternalBuiltinPrefix)) |
| 538 |
return false; |
| 539 |
// Remove the __builtin_spirv_ prefix |
| 540 |
std::string WithoutPrefix = FullDemangled.substr(strlen(kSPIRVName::InternalBuiltinPrefix)); |
| 541 |
// Extract just the function name (before the opening parenthesis) |
| 542 |
size_t ParenPos = WithoutPrefix.find('('); |
| 543 |
if (ParenPos != std::string::npos) |
| 544 |
DemangledName = WithoutPrefix.substr(0, ParenPos); |
| 545 |
else |
| 546 |
DemangledName = WithoutPrefix; |
| 547 |
} else { |
| 548 |
// Demangling failed (e.g., for bfloat types in LLVM 16) |
| 549 |
// Fall back to extracting function name directly from the mangled name |
| 550 |
// Format: _Z<len>__builtin_spirv_<FunctionName><TypeEncoding> |
| 551 |
// All conversion function names end with "EXT" or "INTEL" |
| 552 |
StringRef AfterPrefix = Name.substr(Start + strlen(kSPIRVName::InternalBuiltinPrefix)); |
| 553 |
|
| 554 |
size_t ExtPos = AfterPrefix.find("EXT"); |
| 555 |
size_t IntelPos = AfterPrefix.find("INTEL"); |
| 556 |
size_t FuncNameEnd = StringRef::npos; |
| 557 |
|
| 558 |
if (ExtPos != StringRef::npos && IntelPos != StringRef::npos) |
| 559 |
FuncNameEnd = std::min(ExtPos + 3, IntelPos + 5); // +3 for "EXT", +5 for "INTEL" |
| 560 |
else if (ExtPos != StringRef::npos) |
| 561 |
FuncNameEnd = ExtPos + 3; |
| 562 |
else if (IntelPos != StringRef::npos) |
| 563 |
FuncNameEnd = IntelPos + 5; |
| 564 |
|
| 565 |
if (FuncNameEnd == StringRef::npos) |
| 566 |
DemangledName = AfterPrefix.str(); |
| 567 |
else |
| 568 |
DemangledName = AfterPrefix.substr(0, FuncNameEnd).str(); |
| 569 |
} |
| 570 |
|
| 571 |
return true; |
| 572 |
} |
| 573 |
|
| 574 |
// Check if a mangled type Name is unsigned |
| 575 |
bool isMangledTypeUnsigned(char Mangled) { |
| 576 |
return Mangled == 'h' /* uchar */ |
| 577 |
|| Mangled == 't' /* ushort */ |
| 578 |
|| Mangled == 'j' /* uint */ |
| 579 |
|| Mangled == 'm' /* ulong */; |
| 580 |
} |
| 581 |
|
| 582 |
// Check if a mangled type Name is signed |
| 583 |
bool isMangledTypeSigned(char Mangled) { |
| 584 |
return Mangled == 'c' /* char */ |
| 585 |
|| Mangled == 'a' /* signed char */ |
| 586 |
|| Mangled == 's' /* short */ |
| 587 |
|| Mangled == 'i' /* int */ |
| 588 |
|| Mangled == 'l' /* long */; |
| 589 |
} |
| 590 |
|
| 591 |
// Check if a mangled type Name is floating point (excludes half) |
| 592 |
bool isMangledTypeFP(char Mangled) { |
| 593 |
return Mangled == 'f' /* float */ |
| 594 |
|| Mangled == 'd'; /* double */ |
| 595 |
} |
| 596 |
|
| 597 |
// Check if a mangled type Name is half |
| 598 |
bool isMangledTypeHalf(std::string Mangled) { |
| 599 |
return Mangled == "Dh"; /* half */ |
| 600 |
} |
| 601 |
|
| 602 |
void eraseSubstitutionFromMangledName(std::string &MangledName) { |
| 603 |
auto Len = MangledName.length(); |
| 604 |
while (Len >= 2 && MangledName.substr(Len - 2, 2) == "S_") { |
| 605 |
Len -= 2; |
| 606 |
MangledName.erase(Len, 2); |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
ParamType lastFuncParamType(StringRef MangledName) { |
| 611 |
std::string Copy(MangledName); |
| 612 |
eraseSubstitutionFromMangledName(Copy); |
| 613 |
char Mangled = Copy.back(); |
| 614 |
std::string Mangled2 = Copy.substr(Copy.size() - 2); |
| 615 |
|
| 616 |
std::string Mangled5 = Copy.substr(Copy.size() - 5); |
| 617 |
if (Mangled5 == "DF16b") { |
| 618 |
return ParamType::FLOAT; |
| 619 |
} |
| 620 |
|
| 621 |
if (isMangledTypeFP(Mangled) || isMangledTypeHalf(Mangled2)) { |
| 622 |
return ParamType::FLOAT; |
| 623 |
} else if (isMangledTypeUnsigned(Mangled)) { |
| 624 |
return ParamType::UNSIGNED; |
| 625 |
} else if (isMangledTypeSigned(Mangled)) { |
| 626 |
return ParamType::SIGNED; |
| 627 |
} |
| 628 |
|
| 629 |
return ParamType::UNKNOWN; |
| 630 |
} |
| 631 |
|
| 632 |
// Check if the last argument is signed |
| 633 |
bool isLastFuncParamSigned(StringRef MangledName) { |
| 634 |
return lastFuncParamType(MangledName) == ParamType::SIGNED; |
| 635 |
} |
| 636 |
|
| 637 |
// Check if a mangled function Name contains unsigned atomic type |
| 638 |
bool containsUnsignedAtomicType(StringRef Name) { |
| 639 |
auto Loc = Name.find(kMangledName::AtomicPrefixIncoming); |
| 640 |
if (Loc == StringRef::npos) |
| 641 |
return false; |
| 642 |
return isMangledTypeUnsigned( |
| 643 |
Name[Loc + strlen(kMangledName::AtomicPrefixIncoming)]); |
| 644 |
} |
| 645 |
|
| 646 |
Constant *castToVoidFuncPtr(Function *F) { |
| 647 |
auto T = getVoidFuncPtrType(F->getParent()); |
| 648 |
return ConstantExpr::getBitCast(F, T); |
| 649 |
} |
| 650 |
|
| 651 |
bool hasArrayArg(Function *F) { |
| 652 |
for (auto I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { |
| 653 |
LLVM_DEBUG(dbgs() << "[hasArrayArg] " << *I << '\n'); |
| 654 |
if (I->getType()->isArrayTy()) { |
| 655 |
return true; |
| 656 |
} |
| 657 |
} |
| 658 |
return false; |
| 659 |
} |
| 660 |
|
| 661 |
/// Convert a struct name from the name given to it in Itanium name mangling to |
| 662 |
/// the name given to it as an LLVM opaque struct. |
| 663 |
static std::string demangleBuiltinOpenCLTypeName(StringRef MangledStructName) { |
| 664 |
assert(MangledStructName.startswith("ocl_") && |
| 665 |
"Not a valid builtin OpenCL mangled name"); |
| 666 |
// Bare structure type that starts with ocl_ is a builtin opencl type. |
| 667 |
// See clang/lib/CodeGen/CGOpenCLRuntime for how these map to LLVM types |
| 668 |
// and clang/lib/AST/ItaniumMangle for how they are mangled. |
| 669 |
// In general, ocl_<foo> is mapped to pointer-to-%opencl.<foo>, but |
| 670 |
// there is some variance around whether or not _t is included in the |
| 671 |
// mangled name. |
| 672 |
std::string LlvmStructName = StringSwitch<StringRef>(MangledStructName) |
| 673 |
.Case("ocl_sampler", "opencl.sampler_t") |
| 674 |
.Case("ocl_event", "opencl.event_t") |
| 675 |
.Case("ocl_clkevent", "opencl.clk_event_t") |
| 676 |
.Case("ocl_queue", "opencl.queue_t") |
| 677 |
.Case("ocl_reserveid", "opencl.reserve_id_t") |
| 678 |
.Default("") |
| 679 |
.str(); |
| 680 |
if (LlvmStructName.empty()) { |
| 681 |
LlvmStructName = "opencl."; |
| 682 |
LlvmStructName += MangledStructName.substr(4); // Strip off ocl_ |
| 683 |
if (!MangledStructName.endswith("_t")) |
| 684 |
LlvmStructName += "_t"; |
| 685 |
} |
| 686 |
return LlvmStructName; |
| 687 |
} |
| 688 |
|
| 689 |
/// Convert a C/C++ type name into an LLVM type, if it's a basic integer or |
| 690 |
/// floating point type. |
| 691 |
static Type *parsePrimitiveType(LLVMContext &Ctx, StringRef Name) { |
| 692 |
return StringSwitch<Type *>(Name) |
| 693 |
.Cases("char", "signed char", "unsigned char", Type::getInt8Ty(Ctx)) |
| 694 |
.Cases("short", "unsigned short", Type::getInt16Ty(Ctx)) |
| 695 |
.Cases("int", "unsigned int", Type::getInt32Ty(Ctx)) |
| 696 |
.Cases("long", "unsigned long", Type::getInt64Ty(Ctx)) |
| 697 |
.Cases("long long", "unsigned long long", Type::getInt64Ty(Ctx)) |
| 698 |
.Case("half", Type::getHalfTy(Ctx)) |
| 699 |
.Case("float", Type::getFloatTy(Ctx)) |
| 700 |
.Case("double", Type::getDoubleTy(Ctx)) |
| 701 |
.Case("void", Type::getInt8Ty(Ctx)) |
| 702 |
.Default(nullptr); |
| 703 |
} |
| 704 |
|
| 705 |
} // namespace SPIRV |
| 706 |
|
| 707 |
namespace { |
| 708 |
|
| 709 |
// Return the value for when the dimension index of a builtin is out of range. |
| 710 |
uint64_t getBuiltinOutOfRangeValue(StringRef VarName) { |
| 711 |
assert(VarName.startswith("__spirv_BuiltIn")); |
| 712 |
return StringSwitch<uint64_t>(VarName) |
| 713 |
.EndsWith("GlobalSize", 1) |
| 714 |
.EndsWith("NumWorkgroups", 1) |
| 715 |
.EndsWith("WorkgroupSize", 1) |
| 716 |
.EndsWith("EnqueuedWorkgroupSize", 1) |
| 717 |
.Default(0); |
| 718 |
} |
| 719 |
|
| 720 |
} // anonymous namespace |
| 721 |
|
| 722 |
// The demangler node hierarchy doesn't use LLVM's RTTI helper functions (as it |
| 723 |
// also needs to live in libcxxabi). By specializing this implementation here, |
| 724 |
// we can add support for these functions. |
| 725 |
#define NODE(X) \ |
| 726 |
template <typename From> struct llvm::isa_impl<itanium_demangle::X, From> { \ |
| 727 |
static inline bool doit(const From &Val) { \ |
| 728 |
return Val.getKind() == itanium_demangle::Node::K##X; \ |
| 729 |
} \ |
| 730 |
}; |
| 731 |
#include "llvm/Demangle/ItaniumNodes.def" |
| 732 |
|
| 733 |
namespace SPIRV { |
| 734 |
|
| 735 |
namespace { |
| 736 |
// An allocator to use with the demangler API. |
| 737 |
class DefaultAllocator { |
| 738 |
BumpPtrAllocator Alloc; |
| 739 |
|
| 740 |
public: |
| 741 |
void reset() { Alloc.Reset(); } |
| 742 |
|
| 743 |
template <typename T, typename... Args> T *makeNode(Args &&...ArgList) { |
| 744 |
return new (Alloc.Allocate(sizeof(T), alignof(T))) |
| 745 |
T(std::forward<Args>(ArgList)...); |
| 746 |
} |
| 747 |
|
| 748 |
void *allocateNodeArray(size_t Sz) { |
| 749 |
using namespace llvm::itanium_demangle; |
| 750 |
return Alloc.Allocate(sizeof(Node *) * Sz, alignof(Node *)); |
| 751 |
} |
| 752 |
}; |
| 753 |
} // unnamed namespace |
| 754 |
|
| 755 |
static StringRef stringify(const itanium_demangle::NameType *Node) { |
| 756 |
const itanium_demangle::StringView Str = Node->getName(); |
| 757 |
return StringRef(Str.begin(), Str.size()); |
| 758 |
} |
| 759 |
|
| 760 |
/// Convert a mangled name that represents a basic integer, floating-point, |
| 761 |
/// etc. type into the corresponding LLVM type. |
| 762 |
static Type *getPrimitiveType(LLVMContext &Ctx, |
| 763 |
const llvm::itanium_demangle::Node *N) { |
| 764 |
using namespace llvm::itanium_demangle; |
| 765 |
if (auto *Name = dyn_cast<NameType>(N)) { |
| 766 |
return parsePrimitiveType(Ctx, stringify(Name)); |
| 767 |
} |
| 768 |
if (auto *BitInt = dyn_cast<BitIntType>(N)) { |
| 769 |
unsigned BitWidth = 0; |
| 770 |
BitInt->match([&](const Node *NodeSize, bool) { |
| 771 |
const StringRef SizeStr(stringify(cast<NameType>(NodeSize))); |
| 772 |
SizeStr.getAsInteger(10, BitWidth); |
| 773 |
}); |
| 774 |
return Type::getIntNTy(Ctx, BitWidth); |
| 775 |
} |
| 776 |
if (auto *FP = dyn_cast<BinaryFPType>(N)) { |
| 777 |
StringRef SizeStr; |
| 778 |
FP->match([&](const Node *NodeDimension) { |
| 779 |
SizeStr = stringify(cast<NameType>(NodeDimension)); |
| 780 |
}); |
| 781 |
return StringSwitch<Type *>(SizeStr) |
| 782 |
.Case("16", Type::getHalfTy(Ctx)) |
| 783 |
.Case("32", Type::getFloatTy(Ctx)) |
| 784 |
.Case("64", Type::getDoubleTy(Ctx)) |
| 785 |
.Case("128", Type::getFP128Ty(Ctx)) |
| 786 |
.Default(nullptr); |
| 787 |
} |
| 788 |
return nullptr; |
| 789 |
} |
| 790 |
|
| 791 |
template <typename FnType> |
| 792 |
static TypedPointerType * |
| 793 |
parseNode(Module *M, const llvm::itanium_demangle::Node *ParamType, |
| 794 |
FnType GetStructType) { |
| 795 |
using namespace llvm::itanium_demangle; |
| 796 |
Type *PointeeTy = nullptr; |
| 797 |
unsigned AS = 0; |
| 798 |
|
| 799 |
if (auto *Name = dyn_cast<NameType>(ParamType)) { |
| 800 |
// This corresponds to a simple class name. Since we only care about |
| 801 |
// pointer element types, the only relevant names are those corresponding |
| 802 |
// to the OpenCL special types (which all begin with "ocl_"). |
| 803 |
StringRef Arg(stringify(Name)); |
| 804 |
if (Arg.startswith("ocl_")) { |
| 805 |
const std::string StructName = demangleBuiltinOpenCLTypeName(Arg); |
| 806 |
PointeeTy = GetStructType(StructName); |
| 807 |
} else if (Arg.consume_front("__spirv_")) { |
| 808 |
// This is a pointer to a SPIR-V OpType* opaque struct. In general, |
| 809 |
// convert __spirv_<Type>[__Suffix] to %spirv.Type[._Suffix] |
| 810 |
auto NameSuffixPair = Arg.split('_'); |
| 811 |
std::string StructName = "spirv."; |
| 812 |
StructName += NameSuffixPair.first; |
| 813 |
if (!NameSuffixPair.second.empty()) { |
| 814 |
StructName += "."; |
| 815 |
StructName += NameSuffixPair.second; |
| 816 |
} |
| 817 |
PointeeTy = GetStructType(StructName); |
| 818 |
} else if (Arg == "ndrange_t") { |
| 819 |
PointeeTy = GetStructType(Arg); |
| 820 |
} |
| 821 |
} else if (auto *P = dyn_cast<itanium_demangle::PointerType>(ParamType)) { |
| 822 |
const Node *Pointee = P->getPointee(); |
| 823 |
|
| 824 |
// Strip through all of the qualifiers on the pointee type. |
| 825 |
while (true) { |
| 826 |
if (auto *VendorTy = dyn_cast<VendorExtQualType>(Pointee)) { |
| 827 |
Pointee = VendorTy->getTy(); |
| 828 |
StringRef Qualifier(VendorTy->getExt().begin(), |
| 829 |
VendorTy->getExt().size()); |
| 830 |
if (Qualifier.consume_front("AS")) { |
| 831 |
Qualifier.getAsInteger(10, AS); |
| 832 |
} |
| 833 |
} else if (auto *Qual = dyn_cast<QualType>(Pointee)) { |
| 834 |
Pointee = Qual->getChild(); |
| 835 |
} else { |
| 836 |
break; |
| 837 |
} |
| 838 |
} |
| 839 |
|
| 840 |
if (auto *Name = dyn_cast<NameType>(Pointee)) { |
| 841 |
StringRef MangledStructName(stringify(Name)); |
| 842 |
if (MangledStructName.consume_front("__spirv_")) { |
| 843 |
// This is a pointer to a SPIR-V OpType* opaque struct. In general, |
| 844 |
// convert __spirv_<Type>[__Suffix] to %spirv.Type[._Suffix] |
| 845 |
auto NameSuffixPair = MangledStructName.split('_'); |
| 846 |
std::string StructName = "spirv."; |
| 847 |
StructName += NameSuffixPair.first; |
| 848 |
if (!NameSuffixPair.second.empty()) { |
| 849 |
StructName += "."; |
| 850 |
StructName += NameSuffixPair.second; |
| 851 |
} |
| 852 |
PointeeTy = GetStructType(StructName); |
| 853 |
} else if (MangledStructName.startswith("opencl.")) { |
| 854 |
PointeeTy = GetStructType(MangledStructName); |
| 855 |
} else if (MangledStructName.startswith("ocl_")) { |
| 856 |
const std::string StructName = |
| 857 |
demangleBuiltinOpenCLTypeName(MangledStructName); |
| 858 |
PointeeTy = TypedPointerType::get(GetStructType(StructName), 0); |
| 859 |
} else { |
| 860 |
PointeeTy = parsePrimitiveType(M->getContext(), MangledStructName); |
| 861 |
} |
| 862 |
} else if (auto *Ty = getPrimitiveType(M->getContext(), Pointee)) { |
| 863 |
PointeeTy = Ty; |
| 864 |
} else if (auto *Vec = dyn_cast<itanium_demangle::VectorType>(Pointee)) { |
| 865 |
unsigned ElemCount = 0; |
| 866 |
const StringRef ElemCountStr( |
| 867 |
stringify(cast<NameType>(Vec->getDimension()))); |
| 868 |
ElemCountStr.getAsInteger(10, ElemCount); |
| 869 |
if (auto *Ty = getPrimitiveType(M->getContext(), Vec->getBaseType())) { |
| 870 |
PointeeTy = llvm::VectorType::get(Ty, ElemCount, false); |
| 871 |
} |
| 872 |
} else if (llvm::isa<itanium_demangle::PointerType>(Pointee)) { |
| 873 |
PointeeTy = parseNode(M, Pointee, GetStructType); |
| 874 |
} else { |
| 875 |
// Other possible pointee types do not correspond to any of the special |
| 876 |
// struct types were are looking for here. |
| 877 |
} |
| 878 |
} else if (auto *VendorTy = dyn_cast<VendorExtQualType>(ParamType)) { |
| 879 |
// This is a block parameter. Decode the pointee type as if it were a |
| 880 |
// void (*)(void) function pointer type. |
| 881 |
if (VendorTy->getExt() == "block_pointer") { |
| 882 |
PointeeTy = |
| 883 |
llvm::FunctionType::get(Type::getVoidTy(M->getContext()), false); |
| 884 |
} |
| 885 |
} else { |
| 886 |
// Other parameter types are not likely to be pointer types, so we can |
| 887 |
// ignore these. |
| 888 |
} |
| 889 |
return PointeeTy ? TypedPointerType::get(PointeeTy, AS) : nullptr; |
| 890 |
} |
| 891 |
|
| 892 |
bool getParameterTypes(Function *F, SmallVectorImpl<Type *> &ArgTys, |
| 893 |
std::function<std::string(StringRef)> NameMapFn) { |
| 894 |
using namespace llvm::itanium_demangle; |
| 895 |
// If there's no mangled name, we can't do anything. Also, if there's no |
| 896 |
// parameters, do nothing. |
| 897 |
StringRef Name = F->getName(); |
| 898 |
if (!Name.startswith("_Z") || F->arg_empty()) |
| 899 |
return Name.startswith("_Z"); |
| 900 |
|
| 901 |
Module *M = F->getParent(); |
| 902 |
auto GetStructType = [&](StringRef Name) { |
| 903 |
return getOrCreateOpaqueStructType(M, NameMapFn ? NameMapFn(Name) : Name); |
| 904 |
}; |
| 905 |
|
| 906 |
// Start by filling in a skeleton of information we can get from the LLVM type |
| 907 |
// itself. |
| 908 |
ArgTys.clear(); |
| 909 |
auto *FT = F->getFunctionType(); |
| 910 |
ArgTys.reserve(FT->getNumParams()); |
| 911 |
bool HasSret = false; |
| 912 |
for (Argument &Arg : F->args()) { |
| 913 |
if (!Arg.getType()->isPointerTy()) |
| 914 |
ArgTys.push_back(Arg.getType()); |
| 915 |
else if (Type *Ty = Arg.getParamStructRetType()) { |
| 916 |
assert(!HasSret && &Arg == F->getArg(0) && |
| 917 |
"sret parameter should only appear on the first argument"); |
| 918 |
HasSret = true; |
| 919 |
unsigned AS = Arg.getType()->getPointerAddressSpace(); |
| 920 |
if (auto *STy = dyn_cast<StructType>(Ty)) |
| 921 |
ArgTys.push_back( |
| 922 |
TypedPointerType::get(GetStructType(STy->getName()), AS)); |
| 923 |
else |
| 924 |
ArgTys.push_back(TypedPointerType::get(Ty, AS)); |
| 925 |
} else { |
| 926 |
ArgTys.push_back(Arg.getType()); |
| 927 |
} |
| 928 |
} |
| 929 |
|
| 930 |
// Skip the first argument if it's an sret parameter--this would be an |
| 931 |
// implicit parameter not recognized as part of the function parameters. |
| 932 |
auto *ArgIter = ArgTys.begin(); |
| 933 |
if (HasSret) |
| 934 |
++ArgIter; |
| 935 |
|
| 936 |
// Demangle the function arguments. If we get an input name of |
| 937 |
// "_Z12write_imagei20ocl_image1d_array_woDv2_iiDv4_i", then we expect |
| 938 |
// that Demangler.getFunctionParameters will return |
| 939 |
// "(ocl_image1d_array_wo, int __vector(2), int, int __vector(4))" (in other |
| 940 |
// words, the stuff between the parentheses if you ran C++ filt, including |
| 941 |
// the parentheses itself). |
| 942 |
const StringRef MangledName(F->getName()); |
| 943 |
ManglingParser<DefaultAllocator> Demangler(MangledName.begin(), |
| 944 |
MangledName.end()); |
| 945 |
// We expect to see only function name encodings here. If it's not a function |
| 946 |
// name encoding, bail out. |
| 947 |
auto *RootNode = dyn_cast_or_null<FunctionEncoding>(Demangler.parse()); |
| 948 |
if (!RootNode) |
| 949 |
return false; |
| 950 |
|
| 951 |
// Get the parameter list. If the function is a vararg function, drop the last |
| 952 |
// parameter. |
| 953 |
NodeArray Params = RootNode->getParams(); |
| 954 |
if (F->isVarArg()) { |
| 955 |
bool HasVarArgParam = false; |
| 956 |
if (!Params.empty()) { |
| 957 |
if (auto *Name = dyn_cast<NameType>(Params[Params.size() - 1])) { |
| 958 |
if (stringify(Name) == "...") |
| 959 |
HasVarArgParam = true; |
| 960 |
} |
| 961 |
} |
| 962 |
if (HasVarArgParam) { |
| 963 |
Params = NodeArray(Params.begin(), Params.size() - 1); |
| 964 |
} else { |
| 965 |
LLVM_DEBUG(dbgs() << "[getParameterTypes] function " << MangledName |
| 966 |
<< " was expected to have a varargs parameter\n"); |
| 967 |
return false; |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
// Sanity check that the name mangling matches up to the expected number of |
| 972 |
// arguments. |
| 973 |
if (Params.size() != (size_t)(ArgTys.end() - ArgIter)) { |
| 974 |
LLVM_DEBUG(dbgs() << "[getParameterTypes] function " << MangledName |
| 975 |
<< " appears to have " << Params.size() |
| 976 |
<< " arguments but has " << (ArgTys.end() - ArgIter) |
| 977 |
<< "\n"); |
| 978 |
return false; |
| 979 |
} |
| 980 |
|
| 981 |
// Overwrite the types of pointer-typed arguments with information from |
| 982 |
// demangling. |
| 983 |
bool DemangledSuccessfully = true; |
| 984 |
for (auto *ParamType : Params) { |
| 985 |
Type *ArgTy = *ArgIter; |
| 986 |
Type *DemangledTy = parseNode(M, ParamType, GetStructType); |
| 987 |
if (ArgTy->isPointerTy() && DemangledTy == nullptr) { |
| 988 |
DemangledTy = TypedPointerType::get(Type::getInt8Ty(ArgTy->getContext()), |
| 989 |
ArgTy->getPointerAddressSpace()); |
| 990 |
LLVM_DEBUG(dbgs() << "Failed to recover type of argument " << *ArgTy |
| 991 |
<< " of function " << F->getName() << "\n"); |
| 992 |
DemangledSuccessfully = false; |
| 993 |
} else if (ArgTy->isTargetExtTy() || !DemangledTy) |
| 994 |
DemangledTy = ArgTy; |
| 995 |
if (auto *TPT = dyn_cast<TypedPointerType>(DemangledTy)) |
| 996 |
if (ArgTy->isPointerTy() && |
| 997 |
TPT->getAddressSpace() != ArgTy->getPointerAddressSpace()) |
| 998 |
DemangledTy = TypedPointerType::get(TPT->getElementType(), |
| 999 |
ArgTy->getPointerAddressSpace()); |
| 1000 |
*ArgIter++ = DemangledTy; |
| 1001 |
} |
| 1002 |
return DemangledSuccessfully; |
| 1003 |
} |
| 1004 |
|
| 1005 |
CallInst *mutateCallInst( |
| 1006 |
Module *M, CallInst *CI, |
| 1007 |
std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate, |
| 1008 |
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) { |
| 1009 |
LLVM_DEBUG(dbgs() << "[mutateCallInst] " << *CI); |
| 1010 |
|
| 1011 |
auto Args = getArguments(CI); |
| 1012 |
auto NewName = ArgMutate(CI, Args); |
| 1013 |
std::string InstName; |
| 1014 |
if (!CI->getType()->isVoidTy() && CI->hasName()) { |
| 1015 |
InstName = CI->getName().str(); |
| 1016 |
CI->setName(InstName + ".old"); |
| 1017 |
} |
| 1018 |
auto NewCI = addCallInst(M, NewName, CI->getType(), Args, Attrs, CI, Mangle, |
| 1019 |
InstName, TakeFuncName); |
| 1020 |
NewCI->setDebugLoc(CI->getDebugLoc()); |
| 1021 |
LLVM_DEBUG(dbgs() << " => " << *NewCI << '\n'); |
| 1022 |
CI->replaceAllUsesWith(NewCI); |
| 1023 |
CI->eraseFromParent(); |
| 1024 |
return NewCI; |
| 1025 |
} |
| 1026 |
|
| 1027 |
Instruction *mutateCallInst( |
| 1028 |
Module *M, CallInst *CI, |
| 1029 |
std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)> |
| 1030 |
ArgMutate, |
| 1031 |
std::function<Instruction *(CallInst *)> RetMutate, |
| 1032 |
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) { |
| 1033 |
LLVM_DEBUG(dbgs() << "[mutateCallInst] " << *CI); |
| 1034 |
|
| 1035 |
auto Args = getArguments(CI); |
| 1036 |
Type *RetTy = CI->getType(); |
| 1037 |
auto NewName = ArgMutate(CI, Args, RetTy); |
| 1038 |
StringRef InstName = CI->getName(); |
| 1039 |
auto NewCI = addCallInst(M, NewName, RetTy, Args, Attrs, CI, Mangle, InstName, |
| 1040 |
TakeFuncName); |
| 1041 |
auto NewI = RetMutate(NewCI); |
| 1042 |
NewI->takeName(CI); |
| 1043 |
NewI->setDebugLoc(CI->getDebugLoc()); |
| 1044 |
LLVM_DEBUG(dbgs() << " => " << *NewI << '\n'); |
| 1045 |
if (!CI->getType()->isVoidTy()) |
| 1046 |
CI->replaceAllUsesWith(NewI); |
| 1047 |
CI->eraseFromParent(); |
| 1048 |
return NewI; |
| 1049 |
} |
| 1050 |
|
| 1051 |
void mutateFunction( |
| 1052 |
Function *F, |
| 1053 |
std::function<std::string(CallInst *, std::vector<Value *> &)> ArgMutate, |
| 1054 |
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeFuncName) { |
| 1055 |
auto M = F->getParent(); |
| 1056 |
for (auto I = F->user_begin(), E = F->user_end(); I != E;) { |
| 1057 |
if (auto CI = dyn_cast<CallInst>(*I++)) |
| 1058 |
mutateCallInst(M, CI, ArgMutate, Mangle, Attrs, TakeFuncName); |
| 1059 |
} |
| 1060 |
if (F->use_empty()) |
| 1061 |
F->eraseFromParent(); |
| 1062 |
} |
| 1063 |
|
| 1064 |
void mutateFunction( |
| 1065 |
Function *F, |
| 1066 |
std::function<std::string(CallInst *, std::vector<Value *> &, Type *&RetTy)> |
| 1067 |
ArgMutate, |
| 1068 |
std::function<Instruction *(CallInst *)> RetMutate, |
| 1069 |
BuiltinFuncMangleInfo *Mangle, AttributeList *Attrs, bool TakeName) { |
| 1070 |
auto *M = F->getParent(); |
| 1071 |
for (auto I = F->user_begin(), E = F->user_end(); I != E;) { |
| 1072 |
if (auto *CI = dyn_cast<CallInst>(*I++)) |
| 1073 |
mutateCallInst(M, CI, ArgMutate, RetMutate, Mangle, Attrs, TakeName); |
| 1074 |
} |
| 1075 |
if (F->use_empty()) |
| 1076 |
F->eraseFromParent(); |
| 1077 |
} |
| 1078 |
|
| 1079 |
CallInst *addCallInst(Module *M, StringRef FuncName, Type *RetTy, |
| 1080 |
ArrayRef<Value *> Args, AttributeList *Attrs, |
| 1081 |
Instruction *Pos, BuiltinFuncMangleInfo *Mangle, |
| 1082 |
StringRef InstName, bool TakeFuncName) { |
| 1083 |
|
| 1084 |
auto F = getOrCreateFunction(M, RetTy, getTypes(Args), FuncName, Mangle, |
| 1085 |
Attrs, TakeFuncName); |
| 1086 |
// Cannot assign a Name to void typed values |
| 1087 |
auto CI = CallInst::Create(F, Args, RetTy->isVoidTy() ? "" : InstName, Pos); |
| 1088 |
CI->setCallingConv(F->getCallingConv()); |
| 1089 |
CI->setAttributes(F->getAttributes()); |
| 1090 |
return CI; |
| 1091 |
} |
| 1092 |
|
| 1093 |
CallInst *addCallInstSPIRV(Module *M, StringRef FuncName, Type *RetTy, |
| 1094 |
ArrayRef<Value *> Args, AttributeList *Attrs, |
| 1095 |
ArrayRef<Type *> PointerElementTypes, |
| 1096 |
Instruction *Pos, StringRef InstName) { |
| 1097 |
BuiltinFuncMangleInfo BtnInfo; |
| 1098 |
for (unsigned I = 0; I < PointerElementTypes.size(); I++) { |
| 1099 |
if (Args[I]->getType()->isPointerTy()) { |
| 1100 |
assert(cast<PointerType>(Args[I]->getType()) |
| 1101 |
->isOpaqueOrPointeeTypeMatches(PointerElementTypes[I])); |
| 1102 |
BtnInfo.getTypeMangleInfo(I).PointerTy = TypedPointerType::get( |
| 1103 |
PointerElementTypes[I], Args[I]->getType()->getPointerAddressSpace()); |
| 1104 |
} |
| 1105 |
} |
| 1106 |
return addCallInst(M, FuncName, RetTy, Args, Attrs, Pos, &BtnInfo, InstName); |
| 1107 |
} |
| 1108 |
|
| 1109 |
bool isValidVectorSize(unsigned I) { |
| 1110 |
return I == 2 || I == 3 || I == 4 || I == 8 || I == 16; |
| 1111 |
} |
| 1112 |
|
| 1113 |
Value *addVector(Instruction *InsPos, ValueVecRange Range) { |
| 1114 |
size_t VecSize = Range.second - Range.first; |
| 1115 |
if (VecSize == 1) |
| 1116 |
return *Range.first; |
| 1117 |
assert(isValidVectorSize(VecSize) && "Invalid vector size"); |
| 1118 |
IRBuilder<> Builder(InsPos); |
| 1119 |
auto Vec = Builder.CreateVectorSplat(VecSize, *Range.first); |
| 1120 |
unsigned Index = 1; |
| 1121 |
for (++Range.first; Range.first != Range.second; ++Range.first, ++Index) |
| 1122 |
Vec = Builder.CreateInsertElement( |
| 1123 |
Vec, *Range.first, |
| 1124 |
ConstantInt::get(Type::getInt32Ty(InsPos->getContext()), Index, false)); |
| 1125 |
return Vec; |
| 1126 |
} |
| 1127 |
|
| 1128 |
void makeVector(Instruction *InsPos, std::vector<Value *> &Ops, |
| 1129 |
ValueVecRange Range) { |
| 1130 |
auto Vec = addVector(InsPos, Range); |
| 1131 |
Ops.erase(Range.first, Range.second); |
| 1132 |
Ops.push_back(Vec); |
| 1133 |
} |
| 1134 |
|
| 1135 |
Constant *castToInt8Ptr(Constant *V, unsigned Addr = 0) { |
| 1136 |
return ConstantExpr::getBitCast(V, Type::getInt8PtrTy(V->getContext(), Addr)); |
| 1137 |
} |
| 1138 |
|
| 1139 |
PointerType *getInt8PtrTy(PointerType *T) { |
| 1140 |
return Type::getInt8PtrTy(T->getContext(), T->getAddressSpace()); |
| 1141 |
} |
| 1142 |
|
| 1143 |
Value *castToInt8Ptr(Value *V, Instruction *Pos) { |
| 1144 |
return CastInst::CreatePointerCast( |
| 1145 |
V, getInt8PtrTy(cast<PointerType>(V->getType())), "", Pos); |
| 1146 |
} |
| 1147 |
|
| 1148 |
IntegerType *getSizetType(Module *M) { |
| 1149 |
return IntegerType::getIntNTy(M->getContext(), |
| 1150 |
M->getDataLayout().getPointerSizeInBits(0)); |
| 1151 |
} |
| 1152 |
|
| 1153 |
Type *getVoidFuncType(Module *M) { |
| 1154 |
return FunctionType::get(Type::getVoidTy(M->getContext()), false); |
| 1155 |
} |
| 1156 |
|
| 1157 |
Type *getVoidFuncPtrType(Module *M, unsigned AddrSpace) { |
| 1158 |
return PointerType::get(getVoidFuncType(M), AddrSpace); |
| 1159 |
} |
| 1160 |
|
| 1161 |
ConstantInt *getInt64(Module *M, int64_t Value) { |
| 1162 |
return ConstantInt::getSigned(Type::getInt64Ty(M->getContext()), Value); |
| 1163 |
} |
| 1164 |
|
| 1165 |
ConstantInt *getUInt64(Module *M, uint64_t Value) { |
| 1166 |
return ConstantInt::get(Type::getInt64Ty(M->getContext()), Value, false); |
| 1167 |
} |
| 1168 |
|
| 1169 |
Constant *getFloat32(Module *M, float Value) { |
| 1170 |
return ConstantFP::get(Type::getFloatTy(M->getContext()), Value); |
| 1171 |
} |
| 1172 |
|
| 1173 |
ConstantInt *getInt32(Module *M, int Value) { |
| 1174 |
return ConstantInt::get(Type::getInt32Ty(M->getContext()), Value, true); |
| 1175 |
} |
| 1176 |
|
| 1177 |
ConstantInt *getUInt32(Module *M, unsigned Value) { |
| 1178 |
return ConstantInt::get(Type::getInt32Ty(M->getContext()), Value, false); |
| 1179 |
} |
| 1180 |
|
| 1181 |
ConstantInt *getInt(Module *M, int64_t Value) { |
| 1182 |
return Value >> 32 ? getInt64(M, Value) |
| 1183 |
: getInt32(M, static_cast<int32_t>(Value)); |
| 1184 |
} |
| 1185 |
|
| 1186 |
ConstantInt *getUInt(Module *M, uint64_t Value) { |
| 1187 |
return Value >> 32 ? getUInt64(M, Value) |
| 1188 |
: getUInt32(M, static_cast<uint32_t>(Value)); |
| 1189 |
} |
| 1190 |
|
| 1191 |
ConstantInt *getUInt16(Module *M, unsigned short Value) { |
| 1192 |
return ConstantInt::get(Type::getInt16Ty(M->getContext()), Value, false); |
| 1193 |
} |
| 1194 |
|
| 1195 |
std::vector<Value *> getInt32(Module *M, const std::vector<int> &Values) { |
| 1196 |
std::vector<Value *> V; |
| 1197 |
for (auto &I : Values) |
| 1198 |
V.push_back(getInt32(M, I)); |
| 1199 |
return V; |
| 1200 |
} |
| 1201 |
|
| 1202 |
ConstantInt *getSizet(Module *M, uint64_t Value) { |
| 1203 |
return ConstantInt::get(getSizetType(M), Value, false); |
| 1204 |
} |
| 1205 |
|
| 1206 |
/////////////////////////////////////////////////////////////////////////////// |
| 1207 |
// |
| 1208 |
// Functions for getting metadata |
| 1209 |
// |
| 1210 |
/////////////////////////////////////////////////////////////////////////////// |
| 1211 |
int64_t getMDOperandAsInt(MDNode *N, unsigned I) { |
| 1212 |
return mdconst::dyn_extract<ConstantInt>(N->getOperand(I))->getZExtValue(); |
| 1213 |
} |
| 1214 |
|
| 1215 |
// Additional helper function to be reused by getMDOperandAs* helpers |
| 1216 |
Metadata *getMDOperandOrNull(MDNode *N, unsigned I) { |
| 1217 |
if (!N) |
| 1218 |
return nullptr; |
| 1219 |
return N->getOperand(I); |
| 1220 |
} |
| 1221 |
|
| 1222 |
StringRef getMDOperandAsString(MDNode *N, unsigned I) { |
| 1223 |
if (auto *Str = dyn_cast_or_null<MDString>(getMDOperandOrNull(N, I))) |
| 1224 |
return Str->getString(); |
| 1225 |
return ""; |
| 1226 |
} |
| 1227 |
|
| 1228 |
MDNode *getMDOperandAsMDNode(MDNode *N, unsigned I) { |
| 1229 |
return dyn_cast_or_null<MDNode>(getMDOperandOrNull(N, I)); |
| 1230 |
} |
| 1231 |
|
| 1232 |
Type *getMDOperandAsType(MDNode *N, unsigned I) { |
| 1233 |
return cast<ValueAsMetadata>(N->getOperand(I))->getType(); |
| 1234 |
} |
| 1235 |
|
| 1236 |
std::set<std::string> getNamedMDAsStringSet(Module *M, |
| 1237 |
const std::string &MDName) { |
| 1238 |
NamedMDNode *NamedMD = M->getNamedMetadata(MDName); |
| 1239 |
std::set<std::string> StrSet; |
| 1240 |
if (!NamedMD) |
| 1241 |
return StrSet; |
| 1242 |
|
| 1243 |
assert(NamedMD->getNumOperands() > 0 && "Invalid SPIR"); |
| 1244 |
|
| 1245 |
for (unsigned I = 0, E = NamedMD->getNumOperands(); I != E; ++I) { |
| 1246 |
MDNode *MD = NamedMD->getOperand(I); |
| 1247 |
if (!MD || MD->getNumOperands() == 0) |
| 1248 |
continue; |
| 1249 |
for (unsigned J = 0, N = MD->getNumOperands(); J != N; ++J) |
| 1250 |
StrSet.insert(getMDOperandAsString(MD, J).str()); |
| 1251 |
} |
| 1252 |
|
| 1253 |
return StrSet; |
| 1254 |
} |
| 1255 |
|
| 1256 |
std::tuple<unsigned, unsigned, std::string> getSPIRVSource(Module *M) { |
| 1257 |
std::tuple<unsigned, unsigned, std::string> Tup; |
| 1258 |
if (auto N = SPIRVMDWalker(*M).getNamedMD(kSPIRVMD::Source).nextOp()) |
| 1259 |
N.get(std::get<0>(Tup)) |
| 1260 |
.get(std::get<1>(Tup)) |
| 1261 |
.setQuiet(true) |
| 1262 |
.get(std::get<2>(Tup)); |
| 1263 |
return Tup; |
| 1264 |
} |
| 1265 |
|
| 1266 |
ConstantInt *mapUInt(Module *M, ConstantInt *I, |
| 1267 |
std::function<unsigned(unsigned)> F) { |
| 1268 |
return ConstantInt::get(I->getType(), F(I->getZExtValue()), false); |
| 1269 |
} |
| 1270 |
|
| 1271 |
ConstantInt *mapSInt(Module *M, ConstantInt *I, std::function<int(int)> F) { |
| 1272 |
return ConstantInt::get(I->getType(), F(I->getSExtValue()), true); |
| 1273 |
} |
| 1274 |
|
| 1275 |
bool isDecoratedSPIRVFunc(const Function *F, StringRef &UndecoratedName) { |
| 1276 |
if (!F->hasName() || !F->getName().startswith(kSPIRVName::Prefix)) |
| 1277 |
return false; |
| 1278 |
UndecoratedName = F->getName(); |
| 1279 |
return true; |
| 1280 |
} |
| 1281 |
|
| 1282 |
/// Get TypePrimitiveEnum for special OpenCL type except opencl.block. |
| 1283 |
SPIR::TypePrimitiveEnum getOCLTypePrimitiveEnum(StringRef TyName) { |
| 1284 |
return StringSwitch<SPIR::TypePrimitiveEnum>(TyName) |
| 1285 |
.Case("opencl.image1d_ro_t", SPIR::PRIMITIVE_IMAGE1D_RO_T) |
| 1286 |
.Case("opencl.image1d_array_ro_t", SPIR::PRIMITIVE_IMAGE1D_ARRAY_RO_T) |
| 1287 |
.Case("opencl.image1d_buffer_ro_t", SPIR::PRIMITIVE_IMAGE1D_BUFFER_RO_T) |
| 1288 |
.Case("opencl.image2d_ro_t", SPIR::PRIMITIVE_IMAGE2D_RO_T) |
| 1289 |
.Case("opencl.image2d_array_ro_t", SPIR::PRIMITIVE_IMAGE2D_ARRAY_RO_T) |
| 1290 |
.Case("opencl.image2d_depth_ro_t", SPIR::PRIMITIVE_IMAGE2D_DEPTH_RO_T) |
| 1291 |
.Case("opencl.image2d_array_depth_ro_t", |
| 1292 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_RO_T) |
| 1293 |
.Case("opencl.image2d_msaa_ro_t", SPIR::PRIMITIVE_IMAGE2D_MSAA_RO_T) |
| 1294 |
.Case("opencl.image2d_array_msaa_ro_t", |
| 1295 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_RO_T) |
| 1296 |
.Case("opencl.image2d_msaa_depth_ro_t", |
| 1297 |
SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_RO_T) |
| 1298 |
.Case("opencl.image2d_array_msaa_depth_ro_t", |
| 1299 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_RO_T) |
| 1300 |
.Case("opencl.image3d_ro_t", SPIR::PRIMITIVE_IMAGE3D_RO_T) |
| 1301 |
.Case("opencl.image1d_wo_t", SPIR::PRIMITIVE_IMAGE1D_WO_T) |
| 1302 |
.Case("opencl.image1d_array_wo_t", SPIR::PRIMITIVE_IMAGE1D_ARRAY_WO_T) |
| 1303 |
.Case("opencl.image1d_buffer_wo_t", SPIR::PRIMITIVE_IMAGE1D_BUFFER_WO_T) |
| 1304 |
.Case("opencl.image2d_wo_t", SPIR::PRIMITIVE_IMAGE2D_WO_T) |
| 1305 |
.Case("opencl.image2d_array_wo_t", SPIR::PRIMITIVE_IMAGE2D_ARRAY_WO_T) |
| 1306 |
.Case("opencl.image2d_depth_wo_t", SPIR::PRIMITIVE_IMAGE2D_DEPTH_WO_T) |
| 1307 |
.Case("opencl.image2d_array_depth_wo_t", |
| 1308 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_WO_T) |
| 1309 |
.Case("opencl.image2d_msaa_wo_t", SPIR::PRIMITIVE_IMAGE2D_MSAA_WO_T) |
| 1310 |
.Case("opencl.image2d_array_msaa_wo_t", |
| 1311 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_WO_T) |
| 1312 |
.Case("opencl.image2d_msaa_depth_wo_t", |
| 1313 |
SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_WO_T) |
| 1314 |
.Case("opencl.image2d_array_msaa_depth_wo_t", |
| 1315 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_WO_T) |
| 1316 |
.Case("opencl.image3d_wo_t", SPIR::PRIMITIVE_IMAGE3D_WO_T) |
| 1317 |
.Case("opencl.image1d_rw_t", SPIR::PRIMITIVE_IMAGE1D_RW_T) |
| 1318 |
.Case("opencl.image1d_array_rw_t", SPIR::PRIMITIVE_IMAGE1D_ARRAY_RW_T) |
| 1319 |
.Case("opencl.image1d_buffer_rw_t", SPIR::PRIMITIVE_IMAGE1D_BUFFER_RW_T) |
| 1320 |
.Case("opencl.image2d_rw_t", SPIR::PRIMITIVE_IMAGE2D_RW_T) |
| 1321 |
.Case("opencl.image2d_array_rw_t", SPIR::PRIMITIVE_IMAGE2D_ARRAY_RW_T) |
| 1322 |
.Case("opencl.image2d_depth_rw_t", SPIR::PRIMITIVE_IMAGE2D_DEPTH_RW_T) |
| 1323 |
.Case("opencl.image2d_array_depth_rw_t", |
| 1324 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_DEPTH_RW_T) |
| 1325 |
.Case("opencl.image2d_msaa_rw_t", SPIR::PRIMITIVE_IMAGE2D_MSAA_RW_T) |
| 1326 |
.Case("opencl.image2d_array_msaa_rw_t", |
| 1327 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_RW_T) |
| 1328 |
.Case("opencl.image2d_msaa_depth_rw_t", |
| 1329 |
SPIR::PRIMITIVE_IMAGE2D_MSAA_DEPTH_RW_T) |
| 1330 |
.Case("opencl.image2d_array_msaa_depth_rw_t", |
| 1331 |
SPIR::PRIMITIVE_IMAGE2D_ARRAY_MSAA_DEPTH_RW_T) |
| 1332 |
.Case("opencl.image3d_rw_t", SPIR::PRIMITIVE_IMAGE3D_RW_T) |
| 1333 |
.Case("opencl.event_t", SPIR::PRIMITIVE_EVENT_T) |
| 1334 |
.Case("opencl.pipe_ro_t", SPIR::PRIMITIVE_PIPE_RO_T) |
| 1335 |
.Case("opencl.pipe_wo_t", SPIR::PRIMITIVE_PIPE_WO_T) |
| 1336 |
.Case("opencl.reserve_id_t", SPIR::PRIMITIVE_RESERVE_ID_T) |
| 1337 |
.Case("opencl.queue_t", SPIR::PRIMITIVE_QUEUE_T) |
| 1338 |
.Case("opencl.clk_event_t", SPIR::PRIMITIVE_CLK_EVENT_T) |
| 1339 |
.Case("opencl.sampler_t", SPIR::PRIMITIVE_SAMPLER_T) |
| 1340 |
.Case("struct.ndrange_t", SPIR::PRIMITIVE_NDRANGE_T) |
| 1341 |
.Case("opencl.intel_sub_group_avc_mce_payload_t", |
| 1342 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_MCE_PAYLOAD_T) |
| 1343 |
.Case("opencl.intel_sub_group_avc_ime_payload_t", |
| 1344 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_PAYLOAD_T) |
| 1345 |
.Case("opencl.intel_sub_group_avc_ref_payload_t", |
| 1346 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_REF_PAYLOAD_T) |
| 1347 |
.Case("opencl.intel_sub_group_avc_sic_payload_t", |
| 1348 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_SIC_PAYLOAD_T) |
| 1349 |
.Case("opencl.intel_sub_group_avc_mce_result_t", |
| 1350 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_MCE_RESULT_T) |
| 1351 |
.Case("opencl.intel_sub_group_avc_ime_result_t", |
| 1352 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_RESULT_T) |
| 1353 |
.Case("opencl.intel_sub_group_avc_ref_result_t", |
| 1354 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_REF_RESULT_T) |
| 1355 |
.Case("opencl.intel_sub_group_avc_sic_result_t", |
| 1356 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_SIC_RESULT_T) |
| 1357 |
.Case( |
| 1358 |
"opencl.intel_sub_group_avc_ime_result_single_reference_streamout_t", |
| 1359 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_SINGLE_REF_STREAMOUT_T) |
| 1360 |
.Case("opencl.intel_sub_group_avc_ime_result_dual_reference_streamout_t", |
| 1361 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_DUAL_REF_STREAMOUT_T) |
| 1362 |
.Case("opencl.intel_sub_group_avc_ime_single_reference_streamin_t", |
| 1363 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_SINGLE_REF_STREAMIN_T) |
| 1364 |
.Case("opencl.intel_sub_group_avc_ime_dual_reference_streamin_t", |
| 1365 |
SPIR::PRIMITIVE_SUB_GROUP_AVC_IME_DUAL_REF_STREAMIN_T) |
| 1366 |
.Default(SPIR::PRIMITIVE_NONE); |
| 1367 |
} |
| 1368 |
/// Translates LLVM type to descriptor for mangler. |
| 1369 |
/// \param Signed indicates integer type should be translated as signed. |
| 1370 |
/// \param VoidPtr indicates i8* should be translated as void*. |
| 1371 |
static SPIR::RefParamType transTypeDesc(Type *Ty, |
| 1372 |
const BuiltinArgTypeMangleInfo &Info) { |
| 1373 |
bool Signed = Info.IsSigned; |
| 1374 |
unsigned Attr = Info.Attr; |
| 1375 |
bool VoidPtr = Info.IsVoidPtr; |
| 1376 |
if (Info.IsEnum) |
| 1377 |
return SPIR::RefParamType(new SPIR::PrimitiveType(Info.Enum)); |
| 1378 |
if (Info.IsSampler) |
| 1379 |
return SPIR::RefParamType( |
| 1380 |
new SPIR::PrimitiveType(SPIR::PRIMITIVE_SAMPLER_T)); |
| 1381 |
if (Ty->isPointerTy()) |
| 1382 |
Ty = TypedPointerType::get(Type::getInt8Ty(Ty->getContext()), |
| 1383 |
Ty->getPointerAddressSpace()); |
| 1384 |
if (Info.IsAtomic && !isa<TypedPointerType>(Ty)) { |
| 1385 |
BuiltinArgTypeMangleInfo DTInfo = Info; |
| 1386 |
DTInfo.IsAtomic = false; |
| 1387 |
return SPIR::RefParamType(new SPIR::AtomicType(transTypeDesc(Ty, DTInfo))); |
| 1388 |
} |
| 1389 |
if (auto *IntTy = dyn_cast<IntegerType>(Ty)) { |
| 1390 |
switch (IntTy->getBitWidth()) { |
| 1391 |
case 1: |
| 1392 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_BOOL)); |
| 1393 |
case 8: |
| 1394 |
return SPIR::RefParamType(new SPIR::PrimitiveType( |
| 1395 |
Signed ? SPIR::PRIMITIVE_CHAR : SPIR::PRIMITIVE_UCHAR)); |
| 1396 |
case 16: |
| 1397 |
return SPIR::RefParamType(new SPIR::PrimitiveType( |
| 1398 |
Signed ? SPIR::PRIMITIVE_SHORT : SPIR::PRIMITIVE_USHORT)); |
| 1399 |
case 32: |
| 1400 |
return SPIR::RefParamType(new SPIR::PrimitiveType( |
| 1401 |
Signed ? SPIR::PRIMITIVE_INT : SPIR::PRIMITIVE_UINT)); |
| 1402 |
case 64: |
| 1403 |
return SPIR::RefParamType(new SPIR::PrimitiveType( |
| 1404 |
Signed ? SPIR::PRIMITIVE_LONG : SPIR::PRIMITIVE_ULONG)); |
| 1405 |
default: |
| 1406 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_INT)); |
| 1407 |
} |
| 1408 |
} |
| 1409 |
if (Ty->isVoidTy()) |
| 1410 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_VOID)); |
| 1411 |
if (Ty->isHalfTy()) |
| 1412 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_HALF)); |
| 1413 |
if (Ty->isFloatTy()) |
| 1414 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_FLOAT)); |
| 1415 |
if (Ty->isDoubleTy()) |
| 1416 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_DOUBLE)); |
| 1417 |
if (Ty->isBFloatTy()) |
| 1418 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_BFLOAT)); |
| 1419 |
if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) { |
| 1420 |
return SPIR::RefParamType(new SPIR::VectorType( |
| 1421 |
transTypeDesc(VecTy->getElementType(), Info), VecTy->getNumElements())); |
| 1422 |
} |
| 1423 |
if (Ty->isArrayTy()) { |
| 1424 |
return transTypeDesc(TypedPointerType::get(Ty->getArrayElementType(), 0), |
| 1425 |
Info); |
| 1426 |
} |
| 1427 |
if (Ty->isStructTy()) { |
| 1428 |
auto Name = Ty->getStructName(); |
| 1429 |
std::string Tmp; |
| 1430 |
|
| 1431 |
if (Name.startswith(kLLVMTypeName::StructPrefix)) |
| 1432 |
Name = Name.drop_front(strlen(kLLVMTypeName::StructPrefix)); |
| 1433 |
if (Name.startswith(kSPIRVTypeName::PrefixAndDelim)) { |
| 1434 |
Name = Name.substr(sizeof(kSPIRVTypeName::PrefixAndDelim) - 1); |
| 1435 |
Tmp = Name.str(); |
| 1436 |
auto Pos = Tmp.find(kSPIRVTypeName::Delimiter); // first dot |
| 1437 |
while (Pos != std::string::npos) { |
| 1438 |
Tmp[Pos] = '_'; |
| 1439 |
Pos = Tmp.find(kSPIRVTypeName::Delimiter, Pos); |
| 1440 |
} |
| 1441 |
Name = Tmp = kSPIRVName::Prefix + Tmp; |
| 1442 |
} |
| 1443 |
// ToDo: Create a better unique Name for struct without Name |
| 1444 |
if (Name.empty()) { |
| 1445 |
std::ostringstream OS; |
| 1446 |
OS << reinterpret_cast<size_t>(Ty); |
| 1447 |
Name = Tmp = std::string("struct_") + OS.str(); |
| 1448 |
} |
| 1449 |
return SPIR::RefParamType(new SPIR::UserDefinedType(Name.str())); |
| 1450 |
} |
| 1451 |
if (auto *TargetTy = dyn_cast<TargetExtType>(Ty)) { |
| 1452 |
std::string FullName; |
| 1453 |
unsigned AS = 0; |
| 1454 |
{ |
| 1455 |
raw_string_ostream OS(FullName); |
| 1456 |
StringRef Name = TargetTy->getName(); |
| 1457 |
if (Name.consume_front(kSPIRVTypeName::PrefixAndDelim)) { |
| 1458 |
OS << "__spirv_" << Name; |
| 1459 |
AS = getOCLOpaqueTypeAddrSpace( |
| 1460 |
SPIRVOpaqueTypeOpCodeMap::map(Name.str())); |
| 1461 |
} else { |
| 1462 |
OS << Name; |
| 1463 |
} |
| 1464 |
if (!TargetTy->int_params().empty()) |
| 1465 |
OS << "_"; |
| 1466 |
for (Type *InnerTy : TargetTy->type_params()) |
| 1467 |
OS << "_" << convertTypeToPostfix(InnerTy); |
| 1468 |
for (unsigned Param : TargetTy->int_params()) |
| 1469 |
OS << "_" << Param; |
| 1470 |
} |
| 1471 |
// Translate as if it's a pointer to the named struct. |
| 1472 |
auto *Inner = new SPIR::UserDefinedType(FullName); |
| 1473 |
auto *PT = new SPIR::PointerType(Inner); |
| 1474 |
PT->setAddressSpace(static_cast<SPIR::TypeAttributeEnum>( |
| 1475 |
AS + (unsigned)SPIR::ATTR_ADDR_SPACE_FIRST)); |
| 1476 |
return SPIR::RefParamType(PT); |
| 1477 |
} |
| 1478 |
|
| 1479 |
if (auto *TargetTy = dyn_cast<TargetExtType>(Ty)) { |
| 1480 |
std::string FullName; |
| 1481 |
unsigned AS = 0; |
| 1482 |
{ |
| 1483 |
raw_string_ostream OS(FullName); |
| 1484 |
StringRef Name = TargetTy->getName(); |
| 1485 |
if (Name.consume_front(kSPIRVTypeName::PrefixAndDelim)) { |
| 1486 |
OS << "__spirv_" << Name; |
| 1487 |
AS = getOCLOpaqueTypeAddrSpace( |
| 1488 |
SPIRVOpaqueTypeOpCodeMap::map(Name.str())); |
| 1489 |
} else { |
| 1490 |
OS << Name; |
| 1491 |
} |
| 1492 |
if (!TargetTy->int_params().empty()) |
| 1493 |
OS << "_"; |
| 1494 |
for (Type *InnerTy : TargetTy->type_params()) |
| 1495 |
OS << "_" << convertTypeToPostfix(InnerTy); |
| 1496 |
for (unsigned Param : TargetTy->int_params()) |
| 1497 |
OS << "_" << Param; |
| 1498 |
} |
| 1499 |
// Translate as if it's a pointer to the named struct. |
| 1500 |
auto *Inner = new SPIR::UserDefinedType(FullName); |
| 1501 |
auto *PT = new SPIR::PointerType(Inner); |
| 1502 |
PT->setAddressSpace(static_cast<SPIR::TypeAttributeEnum>( |
| 1503 |
AS + (unsigned)SPIR::ATTR_ADDR_SPACE_FIRST)); |
| 1504 |
return SPIR::RefParamType(PT); |
| 1505 |
} |
| 1506 |
|
| 1507 |
if (auto *TPT = dyn_cast<TypedPointerType>(Ty)) { |
| 1508 |
auto *ET = TPT->getElementType(); |
| 1509 |
SPIR::ParamType *EPT = nullptr; |
| 1510 |
if (isa<FunctionType>(ET)) { |
| 1511 |
assert(isVoidFuncTy(cast<FunctionType>(ET)) && "Not supported"); |
| 1512 |
EPT = new SPIR::BlockType; |
| 1513 |
} else if (auto StructTy = dyn_cast<StructType>(ET)) { |
| 1514 |
LLVM_DEBUG(dbgs() << "ptr to struct: " << *Ty << '\n'); |
| 1515 |
auto TyName = StructTy->getStructName(); |
| 1516 |
if (TyName.startswith(kSPR2TypeName::OCLPrefix)) { |
| 1517 |
auto DelimPos = TyName.find_first_of(kSPR2TypeName::Delimiter, |
| 1518 |
strlen(kSPR2TypeName::OCLPrefix)); |
| 1519 |
if (DelimPos != StringRef::npos) |
| 1520 |
TyName = TyName.substr(0, DelimPos); |
| 1521 |
} |
| 1522 |
LLVM_DEBUG(dbgs() << " type Name: " << TyName << '\n'); |
| 1523 |
|
| 1524 |
auto Prim = getOCLTypePrimitiveEnum(TyName); |
| 1525 |
if (StructTy->isOpaque()) { |
| 1526 |
if (TyName == "opencl.block") { |
| 1527 |
auto BlockTy = new SPIR::BlockType; |
| 1528 |
// Handle block with local memory arguments according to OpenCL 2.0 |
| 1529 |
// spec. |
| 1530 |
if (Info.IsLocalArgBlock) { |
| 1531 |
SPIR::RefParamType VoidTyRef( |
| 1532 |
new SPIR::PrimitiveType(SPIR::PRIMITIVE_VOID)); |
| 1533 |
auto VoidPtrTy = new SPIR::PointerType(VoidTyRef); |
| 1534 |
VoidPtrTy->setAddressSpace(SPIR::ATTR_LOCAL); |
| 1535 |
// "__local void *" |
| 1536 |
BlockTy->setParam(0, SPIR::RefParamType(VoidPtrTy)); |
| 1537 |
// "..." |
| 1538 |
BlockTy->setParam(1, SPIR::RefParamType(new SPIR::PrimitiveType( |
| 1539 |
SPIR::PRIMITIVE_VAR_ARG))); |
| 1540 |
} |
| 1541 |
EPT = BlockTy; |
| 1542 |
} else if (Prim != SPIR::PRIMITIVE_NONE) { |
| 1543 |
if (Prim == SPIR::PRIMITIVE_PIPE_RO_T || |
| 1544 |
Prim == SPIR::PRIMITIVE_PIPE_WO_T) { |
| 1545 |
SPIR::RefParamType OpaqueTyRef(new SPIR::PrimitiveType(Prim)); |
| 1546 |
auto OpaquePtrTy = new SPIR::PointerType(OpaqueTyRef); |
| 1547 |
OpaquePtrTy->setAddressSpace(getOCLOpaqueTypeAddrSpace(Prim)); |
| 1548 |
EPT = OpaquePtrTy; |
| 1549 |
} else { |
| 1550 |
EPT = new SPIR::PrimitiveType(Prim); |
| 1551 |
} |
| 1552 |
} |
| 1553 |
} else if (Prim == SPIR::PRIMITIVE_NDRANGE_T) |
| 1554 |
// ndrange_t is not opaque type |
| 1555 |
EPT = new SPIR::PrimitiveType(SPIR::PRIMITIVE_NDRANGE_T); |
| 1556 |
} |
| 1557 |
if (EPT) |
| 1558 |
return SPIR::RefParamType(EPT); |
| 1559 |
|
| 1560 |
if (VoidPtr && ET->isIntegerTy(8)) |
| 1561 |
ET = Type::getVoidTy(ET->getContext()); |
| 1562 |
auto *PT = new SPIR::PointerType(transTypeDesc(ET, Info)); |
| 1563 |
PT->setAddressSpace(static_cast<SPIR::TypeAttributeEnum>( |
| 1564 |
TPT->getAddressSpace() + (unsigned)SPIR::ATTR_ADDR_SPACE_FIRST)); |
| 1565 |
for (unsigned I = SPIR::ATTR_QUALIFIER_FIRST, E = SPIR::ATTR_QUALIFIER_LAST; |
| 1566 |
I <= E; ++I) |
| 1567 |
PT->setQualifier(static_cast<SPIR::TypeAttributeEnum>(I), I & Attr); |
| 1568 |
return SPIR::RefParamType(PT); |
| 1569 |
} |
| 1570 |
LLVM_DEBUG(dbgs() << "[transTypeDesc] " << *Ty << '\n'); |
| 1571 |
assert(0 && "not implemented"); |
| 1572 |
return SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_INT)); |
| 1573 |
} |
| 1574 |
|
| 1575 |
Value *getScalarOrArray(Value *V, unsigned Size, Instruction *Pos) { |
| 1576 |
if (!V->getType()->isPointerTy()) |
| 1577 |
return V; |
| 1578 |
auto GEP = cast<GEPOperator>(V); |
| 1579 |
assert(GEP->getNumOperands() == 3 && "must be a GEP from an array"); |
| 1580 |
assert(GEP->getSourceElementType()->getArrayNumElements() == Size); |
| 1581 |
[[maybe_unused]] auto *OP1 = cast<ConstantInt>(GEP->getOperand(1)); |
| 1582 |
[[maybe_unused]] auto *OP2 = cast<ConstantInt>(GEP->getOperand(2)); |
| 1583 |
assert(OP1->getZExtValue() == 0); |
| 1584 |
assert(OP2->getZExtValue() == 0); |
| 1585 |
return new LoadInst(GEP->getSourceElementType(), GEP->getOperand(0), "", Pos); |
| 1586 |
} |
| 1587 |
|
| 1588 |
Constant *getScalarOrVectorConstantInt(Type *T, uint64_t V, bool IsSigned) { |
| 1589 |
if (auto IT = dyn_cast<IntegerType>(T)) |
| 1590 |
return ConstantInt::get(IT, V); |
| 1591 |
if (auto VT = dyn_cast<FixedVectorType>(T)) { |
| 1592 |
std::vector<Constant *> EV( |
| 1593 |
VT->getNumElements(), |
| 1594 |
getScalarOrVectorConstantInt(VT->getElementType(), V, IsSigned)); |
| 1595 |
return ConstantVector::get(EV); |
| 1596 |
} |
| 1597 |
llvm_unreachable("Invalid type"); |
| 1598 |
return nullptr; |
| 1599 |
} |
| 1600 |
|
| 1601 |
Value *getScalarOrArrayConstantInt(Instruction *Pos, Type *T, unsigned Len, |
| 1602 |
uint64_t V, bool IsSigned) { |
| 1603 |
if (auto IT = dyn_cast<IntegerType>(T)) { |
| 1604 |
assert(Len == 1 && "Invalid length"); |
| 1605 |
return ConstantInt::get(IT, V, IsSigned); |
| 1606 |
} |
| 1607 |
if (isa<PointerType>(T)) { |
| 1608 |
unsigned PointerSize = |
| 1609 |
Pos->getModule()->getDataLayout().getPointerTypeSizeInBits(T); |
| 1610 |
auto *ET = Type::getIntNTy(T->getContext(), PointerSize); |
| 1611 |
assert(cast<PointerType>(T)->isOpaqueOrPointeeTypeMatches(ET) && |
| 1612 |
"Pointer-to-non-size_t arguments are not valid for this call"); |
| 1613 |
auto AT = ArrayType::get(ET, Len); |
| 1614 |
std::vector<Constant *> EV(Len, ConstantInt::get(ET, V, IsSigned)); |
| 1615 |
auto CA = ConstantArray::get(AT, EV); |
| 1616 |
auto Alloca = new AllocaInst(AT, 0, "", Pos); |
| 1617 |
new StoreInst(CA, Alloca, Pos); |
| 1618 |
auto Zero = ConstantInt::getNullValue(Type::getInt32Ty(T->getContext())); |
| 1619 |
Value *Index[] = {Zero, Zero}; |
| 1620 |
auto *Ret = GetElementPtrInst::CreateInBounds(AT, Alloca, Index, "", Pos); |
| 1621 |
LLVM_DEBUG(dbgs() << "[getScalarOrArrayConstantInt] Alloca: " << *Alloca |
| 1622 |
<< ", Return: " << *Ret << '\n'); |
| 1623 |
return Ret; |
| 1624 |
} |
| 1625 |
if (auto AT = dyn_cast<ArrayType>(T)) { |
| 1626 |
auto ET = AT->getArrayElementType(); |
| 1627 |
assert(AT->getArrayNumElements() == Len); |
| 1628 |
std::vector<Constant *> EV(Len, ConstantInt::get(ET, V, IsSigned)); |
| 1629 |
auto Ret = ConstantArray::get(AT, EV); |
| 1630 |
LLVM_DEBUG(dbgs() << "[getScalarOrArrayConstantInt] Array type: " << *AT |
| 1631 |
<< ", Return: " << *Ret << '\n'); |
| 1632 |
return Ret; |
| 1633 |
} |
| 1634 |
llvm_unreachable("Invalid type"); |
| 1635 |
return nullptr; |
| 1636 |
} |
| 1637 |
|
| 1638 |
void dumpUsers(Value *V, StringRef Prompt) { |
| 1639 |
if (!V) |
| 1640 |
return; |
| 1641 |
LLVM_DEBUG(dbgs() << Prompt << " Users of " << *V << " :\n"); |
| 1642 |
for (auto UI = V->user_begin(), UE = V->user_end(); UI != UE; ++UI) |
| 1643 |
LLVM_DEBUG(dbgs() << " " << **UI << '\n'); |
| 1644 |
} |
| 1645 |
|
| 1646 |
std::string getSPIRVTypeName(StringRef BaseName, StringRef Postfixes) { |
| 1647 |
assert(!BaseName.empty() && "Invalid SPIR-V type Name"); |
| 1648 |
auto TN = std::string(kSPIRVTypeName::PrefixAndDelim) + BaseName.str(); |
| 1649 |
if (Postfixes.empty()) |
| 1650 |
return TN; |
| 1651 |
return TN + kSPIRVTypeName::Delimiter + Postfixes.str(); |
| 1652 |
} |
| 1653 |
|
| 1654 |
bool isSPIRVConstantName(StringRef TyName) { |
| 1655 |
if (TyName == getSPIRVTypeName(kSPIRVTypeName::ConstantSampler) || |
| 1656 |
TyName == getSPIRVTypeName(kSPIRVTypeName::ConstantPipeStorage)) |
| 1657 |
return true; |
| 1658 |
|
| 1659 |
return false; |
| 1660 |
} |
| 1661 |
|
| 1662 |
std::string getSPIRVImageSampledTypeName(SPIRVType *Ty) { |
| 1663 |
switch (Ty->getOpCode()) { |
| 1664 |
case OpTypeVoid: |
| 1665 |
return kSPIRVImageSampledTypeName::Void; |
| 1666 |
case OpTypeInt: |
| 1667 |
if (Ty->getIntegerBitWidth() == 32) { |
| 1668 |
if (static_cast<SPIRVTypeInt *>(Ty)->isSigned()) |
| 1669 |
return kSPIRVImageSampledTypeName::Int; |
| 1670 |
else |
| 1671 |
return kSPIRVImageSampledTypeName::UInt; |
| 1672 |
} |
| 1673 |
break; |
| 1674 |
case OpTypeFloat: |
| 1675 |
switch (Ty->getFloatBitWidth()) { |
| 1676 |
case 16: |
| 1677 |
return kSPIRVImageSampledTypeName::Half; |
| 1678 |
case 32: |
| 1679 |
return kSPIRVImageSampledTypeName::Float; |
| 1680 |
default: |
| 1681 |
break; |
| 1682 |
} |
| 1683 |
break; |
| 1684 |
default: |
| 1685 |
break; |
| 1686 |
} |
| 1687 |
llvm_unreachable("Invalid sampled type for image"); |
| 1688 |
return std::string(); |
| 1689 |
} |
| 1690 |
|
| 1691 |
// ToDo: Find a way to represent uint sampled type in LLVM, maybe an |
| 1692 |
// opaque type. |
| 1693 |
Type *getLLVMTypeForSPIRVImageSampledTypePostfix(StringRef Postfix, |
| 1694 |
LLVMContext &Ctx) { |
| 1695 |
if (Postfix == kSPIRVImageSampledTypeName::Void) |
| 1696 |
return Type::getVoidTy(Ctx); |
| 1697 |
if (Postfix == kSPIRVImageSampledTypeName::Float) |
| 1698 |
return Type::getFloatTy(Ctx); |
| 1699 |
if (Postfix == kSPIRVImageSampledTypeName::Half) |
| 1700 |
return Type::getHalfTy(Ctx); |
| 1701 |
if (Postfix == kSPIRVImageSampledTypeName::Int || |
| 1702 |
Postfix == kSPIRVImageSampledTypeName::UInt) |
| 1703 |
return Type::getInt32Ty(Ctx); |
| 1704 |
if (Postfix == kSPIRVImageSampledTypeName::Long || |
| 1705 |
Postfix == kSPIRVImageSampledTypeName::ULong) |
| 1706 |
return Type::getInt64Ty(Ctx); |
| 1707 |
llvm_unreachable("Invalid sampled type postfix"); |
| 1708 |
return nullptr; |
| 1709 |
} |
| 1710 |
|
| 1711 |
std::string convertTypeToPostfix(Type *Ty) { |
| 1712 |
if (Ty->isIntegerTy()) { |
| 1713 |
switch (Ty->getIntegerBitWidth()) { |
| 1714 |
case 8: |
| 1715 |
return "char"; |
| 1716 |
case 16: |
| 1717 |
return "short"; |
| 1718 |
case 32: |
| 1719 |
return "uint"; |
| 1720 |
case 64: |
| 1721 |
return "long"; |
| 1722 |
default: |
| 1723 |
return (Twine("i") + Twine(Ty->getIntegerBitWidth())).str(); |
| 1724 |
} |
| 1725 |
} else if (Ty->isHalfTy()) { |
| 1726 |
return "half"; |
| 1727 |
} else if (Ty->isFloatTy()) { |
| 1728 |
return "float"; |
| 1729 |
} else if (Ty->isDoubleTy()) { |
| 1730 |
return "double"; |
| 1731 |
} else if (Ty->isBFloatTy()) { |
| 1732 |
return "bfloat16"; |
| 1733 |
} else if (Ty->isVoidTy()) { |
| 1734 |
return "void"; |
| 1735 |
} else { |
| 1736 |
report_fatal_error("Unknown LLVM type for element type"); |
| 1737 |
} |
| 1738 |
} |
| 1739 |
|
| 1740 |
std::string getImageBaseTypeName(StringRef Name) { |
| 1741 |
|
| 1742 |
SmallVector<StringRef, 4> SubStrs; |
| 1743 |
const char Delims[] = {kSPR2TypeName::Delimiter, 0}; |
| 1744 |
Name.split(SubStrs, Delims); |
| 1745 |
if (Name.startswith(kSPR2TypeName::OCLPrefix)) { |
| 1746 |
Name = SubStrs[1]; |
| 1747 |
} else { |
| 1748 |
Name = SubStrs[0]; |
| 1749 |
} |
| 1750 |
|
| 1751 |
std::string ImageTyName{Name}; |
| 1752 |
if (hasAccessQualifiedName(Name)) |
| 1753 |
ImageTyName.erase(ImageTyName.size() - 5, 3); |
| 1754 |
|
| 1755 |
return ImageTyName; |
| 1756 |
} |
| 1757 |
|
| 1758 |
size_t getImageOperandsIndex(Op OpCode) { |
| 1759 |
switch (OpCode) { |
| 1760 |
case OpImageRead: |
| 1761 |
case OpImageSampleExplicitLod: |
| 1762 |
return 2; |
| 1763 |
case OpImageWrite: |
| 1764 |
return 3; |
| 1765 |
default: |
| 1766 |
return ~0U; |
| 1767 |
} |
| 1768 |
} |
| 1769 |
|
| 1770 |
SPIRVTypeImageDescriptor getImageDescriptor(Type *Ty) { |
| 1771 |
if (auto *TET = dyn_cast_or_null<TargetExtType>(Ty)) { |
| 1772 |
auto IntParams = TET->int_params(); |
| 1773 |
assert(IntParams.size() > 6 && "Expected type to be an image type"); |
| 1774 |
return SPIRVTypeImageDescriptor(SPIRVImageDimKind(IntParams[0]), |
| 1775 |
IntParams[1], IntParams[2], IntParams[3], |
| 1776 |
IntParams[4], IntParams[5]); |
| 1777 |
} |
| 1778 |
StringRef TyName; |
| 1779 |
[[maybe_unused]] bool IsImg = isOCLImageType(Ty, &TyName); |
| 1780 |
assert(IsImg && "Must be an image type"); |
| 1781 |
return map<SPIRVTypeImageDescriptor>(getImageBaseTypeName(TyName)); |
| 1782 |
} |
| 1783 |
|
| 1784 |
bool eraseIfNoUse(Function *F) { |
| 1785 |
bool Changed = false; |
| 1786 |
if (!F) |
| 1787 |
return Changed; |
| 1788 |
if (!GlobalValue::isInternalLinkage(F->getLinkage()) && !F->isDeclaration()) |
| 1789 |
return Changed; |
| 1790 |
|
| 1791 |
dumpUsers(F, "[eraseIfNoUse] "); |
| 1792 |
for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE;) { |
| 1793 |
auto U = *UI++; |
| 1794 |
if (auto CE = dyn_cast<ConstantExpr>(U)) { |
| 1795 |
if (CE->use_empty()) { |
| 1796 |
CE->dropAllReferences(); |
| 1797 |
Changed = true; |
| 1798 |
} |
| 1799 |
} |
| 1800 |
} |
| 1801 |
if (F->use_empty()) { |
| 1802 |
LLVM_DEBUG(dbgs() << "Erase "; F->printAsOperand(dbgs()); dbgs() << '\n'); |
| 1803 |
F->eraseFromParent(); |
| 1804 |
Changed = true; |
| 1805 |
} |
| 1806 |
return Changed; |
| 1807 |
} |
| 1808 |
|
| 1809 |
void eraseIfNoUse(Value *V) { |
| 1810 |
if (!V->use_empty()) |
| 1811 |
return; |
| 1812 |
if (Constant *C = dyn_cast<Constant>(V)) { |
| 1813 |
C->destroyConstant(); |
| 1814 |
return; |
| 1815 |
} |
| 1816 |
if (Instruction *I = dyn_cast<Instruction>(V)) { |
| 1817 |
if (!I->mayHaveSideEffects()) |
| 1818 |
I->eraseFromParent(); |
| 1819 |
} |
| 1820 |
eraseIfNoUse(dyn_cast<Function>(V)); |
| 1821 |
} |
| 1822 |
|
| 1823 |
bool eraseUselessFunctions(Module *M) { |
| 1824 |
bool Changed = false; |
| 1825 |
for (auto I = M->begin(), E = M->end(); I != E;) |
| 1826 |
Changed |= eraseIfNoUse(&(*I++)); |
| 1827 |
return Changed; |
| 1828 |
} |
| 1829 |
|
| 1830 |
// The mangling algorithm follows OpenCL pipe built-ins clang 3.8 CodeGen rules. |
| 1831 |
static SPIR::MangleError |
| 1832 |
manglePipeOrAddressSpaceCastBuiltin(const SPIR::FunctionDescriptor &Fd, |
| 1833 |
std::string &MangledName) { |
| 1834 |
assert(OCLUtil::isPipeOrAddressSpaceCastBI(Fd.Name) && |
| 1835 |
"Method is expected to be called only for pipe and address space cast " |
| 1836 |
"builtins!"); |
| 1837 |
if (Fd.isNull()) { |
| 1838 |
MangledName.assign(SPIR::FunctionDescriptor::nullString()); |
| 1839 |
return SPIR::MANGLE_NULL_FUNC_DESCRIPTOR; |
| 1840 |
} |
| 1841 |
MangledName.assign("__" + Fd.Name); |
| 1842 |
return SPIR::MANGLE_SUCCESS; |
| 1843 |
} |
| 1844 |
|
| 1845 |
std::string mangleBuiltin(StringRef UniqName, ArrayRef<Type *> ArgTypes, |
| 1846 |
BuiltinFuncMangleInfo *BtnInfo) { |
| 1847 |
if (!BtnInfo) |
| 1848 |
return std::string(UniqName); |
| 1849 |
BtnInfo->init(UniqName); |
| 1850 |
if (BtnInfo->avoidMangling()) |
| 1851 |
return std::string(UniqName); |
| 1852 |
std::string MangledName; |
| 1853 |
LLVM_DEBUG(dbgs() << "[mangle] " << UniqName << " => "); |
| 1854 |
SPIR::FunctionDescriptor FD; |
| 1855 |
FD.Name = BtnInfo->getUnmangledName(); |
| 1856 |
bool BIVarArgNegative = BtnInfo->getVarArg() < 0; |
| 1857 |
|
| 1858 |
if (ArgTypes.empty()) { |
| 1859 |
// Function signature cannot be ()(void, ...) so if there is an ellipsis |
| 1860 |
// it must be ()(...) |
| 1861 |
if (BIVarArgNegative) { |
| 1862 |
FD.Parameters.emplace_back( |
| 1863 |
SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_VOID))); |
| 1864 |
} |
| 1865 |
} else { |
| 1866 |
for (unsigned I = 0, E = BIVarArgNegative ? ArgTypes.size() |
| 1867 |
: (unsigned)BtnInfo->getVarArg(); |
| 1868 |
I != E; ++I) { |
| 1869 |
auto T = ArgTypes[I]; |
| 1870 |
auto MangleInfo = BtnInfo->getTypeMangleInfo(I); |
| 1871 |
if (MangleInfo.PointerTy && T->isPointerTy()) { |
| 1872 |
T = MangleInfo.PointerTy; |
| 1873 |
} |
| 1874 |
FD.Parameters.emplace_back( |
| 1875 |
transTypeDesc(T, BtnInfo->getTypeMangleInfo(I))); |
| 1876 |
} |
| 1877 |
} |
| 1878 |
// Ellipsis must be the last argument of any function |
| 1879 |
if (!BIVarArgNegative) { |
| 1880 |
assert((unsigned)BtnInfo->getVarArg() <= ArgTypes.size() && |
| 1881 |
"invalid index of an ellipsis"); |
| 1882 |
FD.Parameters.emplace_back( |
| 1883 |
SPIR::RefParamType(new SPIR::PrimitiveType(SPIR::PRIMITIVE_VAR_ARG))); |
| 1884 |
} |
| 1885 |
|
| 1886 |
#if defined(SPIRV_SPIR20_MANGLING_REQUIREMENTS) |
| 1887 |
SPIR::NameMangler Mangler(SPIR::SPIR20); |
| 1888 |
Mangler.mangle(FD, MangledName); |
| 1889 |
#else |
| 1890 |
if (OCLUtil::isPipeOrAddressSpaceCastBI(BtnInfo->getUnmangledName())) { |
| 1891 |
manglePipeOrAddressSpaceCastBuiltin(FD, MangledName); |
| 1892 |
} else { |
| 1893 |
SPIR::NameMangler Mangler(SPIR::SPIR20); |
| 1894 |
Mangler.mangle(FD, MangledName); |
| 1895 |
} |
| 1896 |
#endif |
| 1897 |
|
| 1898 |
LLVM_DEBUG(dbgs() << MangledName << '\n'); |
| 1899 |
return MangledName; |
| 1900 |
} |
| 1901 |
|
| 1902 |
/// Check if access qualifier is encoded in the type Name. |
| 1903 |
bool hasAccessQualifiedName(StringRef TyName) { |
| 1904 |
if (TyName.size() < 5) |
| 1905 |
return false; |
| 1906 |
auto Acc = TyName.substr(TyName.size() - 5, 3); |
| 1907 |
return llvm::StringSwitch<bool>(Acc) |
| 1908 |
.Case(kAccessQualPostfix::ReadOnly, true) |
| 1909 |
.Case(kAccessQualPostfix::WriteOnly, true) |
| 1910 |
.Case(kAccessQualPostfix::ReadWrite, true) |
| 1911 |
.Default(false); |
| 1912 |
} |
| 1913 |
|
| 1914 |
SPIRVAccessQualifierKind getAccessQualifier(StringRef TyName) { |
| 1915 |
assert(hasAccessQualifiedName(TyName) && |
| 1916 |
"Type is not qualified with access."); |
| 1917 |
auto Acc = TyName.substr(TyName.size() - 5, 3); |
| 1918 |
return llvm::StringSwitch<SPIRVAccessQualifierKind>(Acc) |
| 1919 |
.Case(kAccessQualPostfix::ReadOnly, AccessQualifierReadOnly) |
| 1920 |
.Case(kAccessQualPostfix::WriteOnly, AccessQualifierWriteOnly) |
| 1921 |
.Case(kAccessQualPostfix::ReadWrite, AccessQualifierReadWrite); |
| 1922 |
} |
| 1923 |
|
| 1924 |
StringRef getAccessQualifierPostfix(SPIRVAccessQualifierKind Access) { |
| 1925 |
switch (Access) { |
| 1926 |
case AccessQualifierReadOnly: |
| 1927 |
return kAccessQualPostfix::ReadOnly; |
| 1928 |
case AccessQualifierWriteOnly: |
| 1929 |
return kAccessQualPostfix::WriteOnly; |
| 1930 |
case AccessQualifierReadWrite: |
| 1931 |
return kAccessQualPostfix::ReadWrite; |
| 1932 |
default: |
| 1933 |
assert(false && "Unrecognized access qualifier!"); |
| 1934 |
return kAccessQualPostfix::ReadWrite; |
| 1935 |
} |
| 1936 |
} |
| 1937 |
|
| 1938 |
bool hasLoopMetadata(const Module *M) { |
| 1939 |
for (const Function &F : *M) |
| 1940 |
for (const BasicBlock &BB : F) { |
| 1941 |
const Instruction *Term = BB.getTerminator(); |
| 1942 |
if (Term && Term->getMetadata("llvm.loop")) |
| 1943 |
return true; |
| 1944 |
} |
| 1945 |
return false; |
| 1946 |
} |
| 1947 |
|
| 1948 |
bool isSPIRVOCLExtInst(const CallInst *CI, OCLExtOpKind *ExtOp) { |
| 1949 |
StringRef DemangledName; |
| 1950 |
if (!oclIsBuiltin(CI->getCalledFunction()->getName(), DemangledName)) |
| 1951 |
return false; |
| 1952 |
StringRef S = DemangledName; |
| 1953 |
if (!S.startswith(kSPIRVName::Prefix)) |
| 1954 |
return false; |
| 1955 |
S = S.drop_front(strlen(kSPIRVName::Prefix)); |
| 1956 |
auto Loc = S.find(kSPIRVPostfix::Divider); |
| 1957 |
auto ExtSetName = S.substr(0, Loc); |
| 1958 |
SPIRVExtInstSetKind Set = SPIRVEIS_Count; |
| 1959 |
if (!SPIRVExtSetShortNameMap::rfind(ExtSetName.str(), &Set)) |
| 1960 |
return false; |
| 1961 |
|
| 1962 |
if (Set != SPIRVEIS_OpenCL) |
| 1963 |
return false; |
| 1964 |
|
| 1965 |
auto ExtOpName = S.substr(Loc + 1); |
| 1966 |
auto PostFixPos = ExtOpName.find("_R"); |
| 1967 |
ExtOpName = ExtOpName.substr(0, PostFixPos); |
| 1968 |
|
| 1969 |
OCLExtOpKind EOC; |
| 1970 |
if (!OCLExtOpMap::rfind(ExtOpName.str(), &EOC)) |
| 1971 |
return false; |
| 1972 |
|
| 1973 |
*ExtOp = EOC; |
| 1974 |
return true; |
| 1975 |
} |
| 1976 |
|
| 1977 |
std::string decodeSPIRVTypeName(StringRef Name, |
| 1978 |
SmallVectorImpl<std::string> &Strs) { |
| 1979 |
SmallVector<StringRef, 4> SubStrs; |
| 1980 |
const char Delim[] = {kSPIRVTypeName::Delimiter, 0}; |
| 1981 |
Name.split(SubStrs, Delim, -1, true); |
| 1982 |
assert(SubStrs.size() >= 2 && "Invalid SPIRV type name"); |
| 1983 |
assert(SubStrs[0] == kSPIRVTypeName::Prefix && "Invalid prefix"); |
| 1984 |
assert((SubStrs.size() == 2 || !SubStrs[2].empty()) && "Invalid postfix"); |
| 1985 |
|
| 1986 |
if (SubStrs.size() > 2) { |
| 1987 |
const char PostDelim[] = {kSPIRVTypeName::PostfixDelim, 0}; |
| 1988 |
SmallVector<StringRef, 4> Postfixes; |
| 1989 |
SubStrs[2].split(Postfixes, PostDelim, -1, true); |
| 1990 |
assert(Postfixes.size() > 1 && Postfixes[0].empty() && "Invalid postfix"); |
| 1991 |
for (unsigned I = 1, E = Postfixes.size(); I != E; ++I) |
| 1992 |
Strs.push_back(std::string(Postfixes[I]).c_str()); |
| 1993 |
} |
| 1994 |
return SubStrs[1].str(); |
| 1995 |
} |
| 1996 |
|
| 1997 |
// Returns true if type(s) and number of elements (if vector) is valid |
| 1998 |
bool checkTypeForSPIRVExtendedInstLowering(IntrinsicInst *II, SPIRVModule *BM) { |
| 1999 |
switch (II->getIntrinsicID()) { |
| 2000 |
case Intrinsic::ceil: |
| 2001 |
case Intrinsic::copysign: |
| 2002 |
case Intrinsic::cos: |
| 2003 |
case Intrinsic::exp: |
| 2004 |
case Intrinsic::exp2: |
| 2005 |
case Intrinsic::fabs: |
| 2006 |
case Intrinsic::floor: |
| 2007 |
case Intrinsic::fma: |
| 2008 |
case Intrinsic::log: |
| 2009 |
case Intrinsic::log10: |
| 2010 |
case Intrinsic::log2: |
| 2011 |
case Intrinsic::maximum: |
| 2012 |
case Intrinsic::maxnum: |
| 2013 |
case Intrinsic::minimum: |
| 2014 |
case Intrinsic::minnum: |
| 2015 |
case Intrinsic::nearbyint: |
| 2016 |
case Intrinsic::pow: |
| 2017 |
case Intrinsic::powi: |
| 2018 |
case Intrinsic::rint: |
| 2019 |
case Intrinsic::round: |
| 2020 |
case Intrinsic::roundeven: |
| 2021 |
case Intrinsic::sin: |
| 2022 |
case Intrinsic::sqrt: |
| 2023 |
case Intrinsic::trunc: { |
| 2024 |
// Although some of the intrinsics above take multiple arguments, it is |
| 2025 |
// sufficient to check arg 0 because the LLVM Verifier will have checked |
| 2026 |
// that all floating point operands have the same type and the second |
| 2027 |
// argument of powi is i32. |
| 2028 |
Type *Ty = II->getType(); |
| 2029 |
if (II->getArgOperand(0)->getType() != Ty) |
| 2030 |
return false; |
| 2031 |
int NumElems = 1; |
| 2032 |
if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) { |
| 2033 |
NumElems = VecTy->getNumElements(); |
| 2034 |
Ty = VecTy->getElementType(); |
| 2035 |
} |
| 2036 |
if (Ty->isBFloatTy() && |
| 2037 |
BM->hasCapability(internal::CapabilityBFloat16ArithmeticINTEL)) |
| 2038 |
return true; |
| 2039 |
if ((!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy()) || |
| 2040 |
(!BM->hasCapability(CapabilityVectorAnyINTEL) && |
| 2041 |
((NumElems > 4) && (NumElems != 8) && (NumElems != 16)))) { |
| 2042 |
BM->SPIRVCK( |
| 2043 |
false, InvalidFunctionCall, II->getCalledOperand()->getName().str()); |
| 2044 |
return false; |
| 2045 |
} |
| 2046 |
break; |
| 2047 |
} |
| 2048 |
case Intrinsic::abs: { |
| 2049 |
Type *Ty = II->getType(); |
| 2050 |
int NumElems = 1; |
| 2051 |
if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) { |
| 2052 |
NumElems = VecTy->getNumElements(); |
| 2053 |
Ty = VecTy->getElementType(); |
| 2054 |
} |
| 2055 |
if (Ty->isBFloatTy() && |
| 2056 |
BM->hasCapability(internal::CapabilityBFloat16ArithmeticINTEL)) |
| 2057 |
return true; |
| 2058 |
if ((!Ty->isIntegerTy()) || |
| 2059 |
(!BM->hasCapability(CapabilityVectorAnyINTEL) && |
| 2060 |
((NumElems > 4) && (NumElems != 8) && (NumElems != 16)))) { |
| 2061 |
BM->SPIRVCK( |
| 2062 |
false, InvalidFunctionCall, II->getCalledOperand()->getName().str()); |
| 2063 |
} |
| 2064 |
break; |
| 2065 |
} |
| 2066 |
default: |
| 2067 |
break; |
| 2068 |
} |
| 2069 |
return true; |
| 2070 |
} |
| 2071 |
|
| 2072 |
CallInst *setAttrByCalledFunc(CallInst *Call) { |
| 2073 |
Function *F = Call->getCalledFunction(); |
| 2074 |
assert(F); |
| 2075 |
if (F->isIntrinsic()) { |
| 2076 |
return Call; |
| 2077 |
} |
| 2078 |
Call->setCallingConv(F->getCallingConv()); |
| 2079 |
Call->setAttributes(F->getAttributes()); |
| 2080 |
return Call; |
| 2081 |
} |
| 2082 |
|
| 2083 |
bool isSPIRVBuiltinVariable(GlobalVariable *GV, |
| 2084 |
SPIRVBuiltinVariableKind *Kind) { |
| 2085 |
if (!GV->hasName() || !getSPIRVBuiltin(GV->getName().str(), *Kind)) |
| 2086 |
return false; |
| 2087 |
return true; |
| 2088 |
} |
| 2089 |
|
| 2090 |
// Variable like GlobalInvolcationId[x] -> get_global_id(x). |
| 2091 |
// Variable like WorkDim -> get_work_dim(). |
| 2092 |
// Replace the following pattern: |
| 2093 |
// %a = addrspacecast i32 addrspace(1)* @__spirv_BuiltInSubgroupMaxSize to |
| 2094 |
// i32 addrspace(4)* |
| 2095 |
// %b = load i32, i32 addrspace(4)* %a, align 4 |
| 2096 |
// %c = load i32, i32 addrspace(4)* %a, align 4 |
| 2097 |
// With: |
| 2098 |
// %b = call spir_func i32 @_Z22get_max_sub_group_sizev() |
| 2099 |
// %c = call spir_func i32 @_Z22get_max_sub_group_sizev() |
| 2100 |
|
| 2101 |
// And replace the following pattern: |
| 2102 |
// %a = addrspacecast <3 x i64> addrspace(1)* @__spirv_BuiltInWorkgroupId to |
| 2103 |
// <3 x i64> addrspace(4)* |
| 2104 |
// %b = load <3 x i64>, <3 x i64> addrspace(4)* %a, align 32 |
| 2105 |
// %c = extractelement <3 x i64> %b, i32 idx |
| 2106 |
// %d = extractelement <3 x i64> %b, i32 idx |
| 2107 |
// With: |
| 2108 |
// %0 = call spir_func i64 @_Z13get_global_idj(i32 0) #1 |
| 2109 |
// %1 = insertelement <3 x i64> undef, i64 %0, i32 0 |
| 2110 |
// %2 = call spir_func i64 @_Z13get_global_idj(i32 1) #1 |
| 2111 |
// %3 = insertelement <3 x i64> %1, i64 %2, i32 1 |
| 2112 |
// %4 = call spir_func i64 @_Z13get_global_idj(i32 2) #1 |
| 2113 |
// %5 = insertelement <3 x i64> %3, i64 %4, i32 2 |
| 2114 |
// %c = extractelement <3 x i64> %5, i32 idx |
| 2115 |
// %d = extractelement <3 x i64> %5, i32 idx |
| 2116 |
// |
| 2117 |
// Replace the following pattern: |
| 2118 |
// %0 = addrspacecast <3 x i64> addrspace(1)* @__spirv_BuiltInWorkgroupSize to |
| 2119 |
// <3 x i64> addrspace(4)* |
| 2120 |
// %1 = getelementptr <3 x i64>, <3 x i64> addrspace(4)* %0, i64 0, i64 0 |
| 2121 |
// %2 = load i64, i64 addrspace(4)* %1, align 32 |
| 2122 |
// With: |
| 2123 |
// %0 = call spir_func i64 @_Z13get_global_idj(i32 0) #1 |
| 2124 |
// %1 = insertelement <3 x i64> undef, i64 %0, i32 0 |
| 2125 |
// %2 = call spir_func i64 @_Z13get_global_idj(i32 1) #1 |
| 2126 |
// %3 = insertelement <3 x i64> %1, i64 %2, i32 1 |
| 2127 |
// %4 = call spir_func i64 @_Z13get_global_idj(i32 2) #1 |
| 2128 |
// %5 = insertelement <3 x i64> %3, i64 %4, i32 2 |
| 2129 |
// %6 = extractelement <3 x i64> %5, i32 0 |
| 2130 |
|
| 2131 |
/// Recursively look through the uses of a global variable, including casts or |
| 2132 |
/// gep offsets, to find all loads of the variable. Gep offsets that are non-0 |
| 2133 |
/// are accumulated in the AccumulatedOffset parameter, which will eventually be |
| 2134 |
/// used to figure out which index of a variable is being used. |
| 2135 |
static void replaceUsesOfBuiltinVar(Value *V, const APInt &AccumulatedOffset, |
| 2136 |
Function *ReplacementFunc, |
| 2137 |
GlobalVariable *GV) { |
| 2138 |
const DataLayout &DL = ReplacementFunc->getParent()->getDataLayout(); |
| 2139 |
SmallVector<Instruction *, 4> InstsToRemove; |
| 2140 |
for (User *U : V->users()) { |
| 2141 |
if (auto *Cast = dyn_cast<CastInst>(U)) { |
| 2142 |
replaceUsesOfBuiltinVar(Cast, AccumulatedOffset, ReplacementFunc, GV); |
| 2143 |
InstsToRemove.push_back(Cast); |
| 2144 |
} else if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { |
| 2145 |
APInt NewOffset = AccumulatedOffset.sextOrTrunc( |
| 2146 |
DL.getIndexSizeInBits(GEP->getPointerAddressSpace())); |
| 2147 |
if (!GEP->accumulateConstantOffset(DL, NewOffset)) |
| 2148 |
llvm_unreachable("Illegal GEP of a SPIR-V builtin variable"); |
| 2149 |
replaceUsesOfBuiltinVar(GEP, NewOffset, ReplacementFunc, GV); |
| 2150 |
InstsToRemove.push_back(GEP); |
| 2151 |
} else if (auto *Load = dyn_cast<LoadInst>(U)) { |
| 2152 |
// Figure out which index the accumulated offset corresponds to. If we |
| 2153 |
// have a weird offset (e.g., trying to load byte 7), bail out. |
| 2154 |
APInt Index; |
| 2155 |
Type *ScalarTy = ReplacementFunc->getReturnType(); |
| 2156 |
if (!ScalarTy->isIntegerTy(1)) { |
| 2157 |
uint64_t Remainder; |
| 2158 |
APInt::udivrem(AccumulatedOffset, ScalarTy->getScalarSizeInBits() / 8, |
| 2159 |
Index, Remainder); |
| 2160 |
if (Remainder != 0) |
| 2161 |
llvm_unreachable("Illegal GEP of a SPIR-V builtin variable"); |
| 2162 |
} |
| 2163 |
|
| 2164 |
IRBuilder<> Builder(Load); |
| 2165 |
Value *Replacement; |
| 2166 |
if (ReplacementFunc->getFunctionType()->getNumParams() == 0) { |
| 2167 |
if (Load->getType() != ScalarTy) |
| 2168 |
llvm_unreachable("Illegal use of a SPIR-V builtin variable"); |
| 2169 |
Replacement = |
| 2170 |
setAttrByCalledFunc(Builder.CreateCall(ReplacementFunc, {})); |
| 2171 |
} else { |
| 2172 |
// The function has an index parameter. |
| 2173 |
if (auto *VecTy = dyn_cast<FixedVectorType>(Load->getType())) { |
| 2174 |
// Reconstruct the original global variable vector because |
| 2175 |
// the load type may not match. |
| 2176 |
// global <3 x i64>, load <6 x i32> |
| 2177 |
VecTy = cast<FixedVectorType>(GV->getValueType()); |
| 2178 |
if (!Index.isZero() || DL.getTypeSizeInBits(VecTy) != |
| 2179 |
DL.getTypeSizeInBits(Load->getType())) |
| 2180 |
llvm_unreachable("Illegal use of a SPIR-V builtin variable"); |
| 2181 |
Replacement = UndefValue::get(VecTy); |
| 2182 |
for (unsigned I = 0; I < VecTy->getNumElements(); I++) { |
| 2183 |
Replacement = Builder.CreateInsertElement( |
| 2184 |
Replacement, |
| 2185 |
setAttrByCalledFunc( |
| 2186 |
Builder.CreateCall(ReplacementFunc, {Builder.getInt32(I)})), |
| 2187 |
Builder.getInt32(I)); |
| 2188 |
} |
| 2189 |
// Insert a bitcast from the reconstructed vector to the load vector |
| 2190 |
// type in case they are different. |
| 2191 |
// Input: |
| 2192 |
// %1 = load <6 x i32>, ptr addrspace(1) %0, align 32 |
| 2193 |
// %2 = extractelement <6 x i32> %1, i32 0 |
| 2194 |
// %3 = add i32 5, %2 |
| 2195 |
// Modified: |
| 2196 |
// < reconstruct global vector elements 0 and 1 > |
| 2197 |
// %2 = insertelement <3 x i64> %0, i64 %1, i32 2 |
| 2198 |
// %3 = bitcast <3 x i64> %2 to <6 x i32> |
| 2199 |
// %4 = extractelement <6 x i32> %3, i32 0 |
| 2200 |
// %5 = add i32 5, %4 |
| 2201 |
Replacement = Builder.CreateBitCast(Replacement, Load->getType()); |
| 2202 |
} else if (Load->getType() == ScalarTy) { |
| 2203 |
Replacement = setAttrByCalledFunc(Builder.CreateCall( |
| 2204 |
ReplacementFunc, {Builder.getInt32(Index.getZExtValue())})); |
| 2205 |
} else { |
| 2206 |
llvm_unreachable("Illegal load type of a SPIR-V builtin variable"); |
| 2207 |
} |
| 2208 |
} |
| 2209 |
Load->replaceAllUsesWith(Replacement); |
| 2210 |
InstsToRemove.push_back(Load); |
| 2211 |
} else { |
| 2212 |
llvm_unreachable("Illegal use of a SPIR-V builtin variable"); |
| 2213 |
} |
| 2214 |
} |
| 2215 |
|
| 2216 |
for (Instruction *I : InstsToRemove) |
| 2217 |
I->eraseFromParent(); |
| 2218 |
} |
| 2219 |
|
| 2220 |
bool lowerBuiltinVariableToCall(GlobalVariable *GV, |
| 2221 |
SPIRVBuiltinVariableKind Kind) { |
| 2222 |
// There might be dead constant users of GV (for example, SPIRVLowerConstExpr |
| 2223 |
// replaces ConstExpr uses but those ConstExprs are not deleted, since LLVM |
| 2224 |
// constants are created on demand as needed and never deleted). |
| 2225 |
// Remove them first! |
| 2226 |
GV->removeDeadConstantUsers(); |
| 2227 |
|
| 2228 |
Module *M = GV->getParent(); |
| 2229 |
LLVMContext &C = M->getContext(); |
| 2230 |
std::string FuncName = GV->getName().str(); |
| 2231 |
Type *GVTy = GV->getValueType(); |
| 2232 |
Type *ReturnTy = GVTy; |
| 2233 |
// Some SPIR-V builtin variables are translated to a function with an index |
| 2234 |
// argument. |
| 2235 |
bool HasIndexArg = |
| 2236 |
ReturnTy->isVectorTy() && |
| 2237 |
!(BuiltInSubgroupEqMask <= Kind && Kind <= BuiltInSubgroupLtMask); |
| 2238 |
if (HasIndexArg) |
| 2239 |
ReturnTy = cast<VectorType>(ReturnTy)->getElementType(); |
| 2240 |
std::vector<Type *> ArgTy; |
| 2241 |
if (HasIndexArg) |
| 2242 |
ArgTy.push_back(Type::getInt32Ty(C)); |
| 2243 |
std::string MangledName; |
| 2244 |
mangleOpenClBuiltin(FuncName, ArgTy, MangledName); |
| 2245 |
Function *Func = M->getFunction(MangledName); |
| 2246 |
if (!Func) { |
| 2247 |
FunctionType *FT = FunctionType::get(ReturnTy, ArgTy, false); |
| 2248 |
Func = Function::Create(FT, GlobalValue::ExternalLinkage, MangledName, M); |
| 2249 |
Func->setCallingConv(CallingConv::SPIR_FUNC); |
| 2250 |
Func->addFnAttr(Attribute::NoUnwind); |
| 2251 |
Func->addFnAttr(Attribute::WillReturn); |
| 2252 |
Func->setDoesNotAccessMemory(); |
| 2253 |
} |
| 2254 |
|
| 2255 |
replaceUsesOfBuiltinVar(GV, APInt(64, 0), Func, GV); |
| 2256 |
return true; |
| 2257 |
} |
| 2258 |
|
| 2259 |
bool lowerBuiltinVariablesToCalls(Module *M) { |
| 2260 |
std::vector<GlobalVariable *> WorkList; |
| 2261 |
for (auto I = M->global_begin(), E = M->global_end(); I != E; ++I) { |
| 2262 |
SPIRVBuiltinVariableKind Kind; |
| 2263 |
if (!isSPIRVBuiltinVariable(&(*I), &Kind)) |
| 2264 |
continue; |
| 2265 |
if (!lowerBuiltinVariableToCall(&(*I), Kind)) |
| 2266 |
return false; |
| 2267 |
WorkList.push_back(&(*I)); |
| 2268 |
} |
| 2269 |
for (auto &I : WorkList) { |
| 2270 |
I->eraseFromParent(); |
| 2271 |
} |
| 2272 |
|
| 2273 |
return true; |
| 2274 |
} |
| 2275 |
|
| 2276 |
/// Transforms SPV-IR work-item builtin calls to SPIRV builtin variables. |
| 2277 |
/// e.g. |
| 2278 |
/// SPV-IR: @_Z33__spirv_BuiltInGlobalInvocationIdi(i) |
| 2279 |
/// is transformed as: |
| 2280 |
/// x = load GlobalInvocationId; extract x, i |
| 2281 |
/// e.g. |
| 2282 |
/// SPV-IR: @_Z22__spirv_BuiltInWorkDim() |
| 2283 |
/// is transformed as: |
| 2284 |
/// load WorkDim |
| 2285 |
bool lowerBuiltinCallsToVariables(Module *M) { |
| 2286 |
LLVM_DEBUG(dbgs() << "Enter lowerBuiltinCallsToVariables\n"); |
| 2287 |
// Store instructions and functions that need to be removed. |
| 2288 |
SmallVector<Value *, 16> ToRemove; |
| 2289 |
for (auto &F : *M) { |
| 2290 |
// Builtins should be declaration only. |
| 2291 |
if (!F.isDeclaration()) |
| 2292 |
continue; |
| 2293 |
StringRef DemangledName; |
| 2294 |
if (!oclIsBuiltin(F.getName(), DemangledName)) |
| 2295 |
continue; |
| 2296 |
LLVM_DEBUG(dbgs() << "Function demangled name: " << DemangledName << '\n'); |
| 2297 |
SmallVector<StringRef, 2> Postfix; |
| 2298 |
// Deprefix "__spirv_" |
| 2299 |
StringRef Name = dePrefixSPIRVName(DemangledName, Postfix); |
| 2300 |
// Lookup SPIRV Builtin map. |
| 2301 |
if (!SPIRVBuiltInNameMap::rfind(Name.str(), nullptr)) |
| 2302 |
continue; |
| 2303 |
std::string BuiltinVarName = DemangledName.str(); |
| 2304 |
LLVM_DEBUG(dbgs() << "builtin variable name: " << BuiltinVarName << '\n'); |
| 2305 |
bool IsVec = F.getFunctionType()->getNumParams() > 0; |
| 2306 |
Type *GVType = |
| 2307 |
IsVec ? FixedVectorType::get(F.getReturnType(), 3) : F.getReturnType(); |
| 2308 |
GlobalVariable *BV = nullptr; |
| 2309 |
// Consider the following LLVM IR: |
| 2310 |
// @__spirv_BuiltInLocalInvocationId = <Global constant> |
| 2311 |
// ..... |
| 2312 |
// define spir_kernel void @kernel1(....) { |
| 2313 |
// %3 = tail call i64 @_Z12get_local_idj(i32 0) |
| 2314 |
// ..... |
| 2315 |
// return void |
| 2316 |
// } |
| 2317 |
// During the OCLToSPIRV pass, the opencl call will get lowered to |
| 2318 |
// yet another global variable with the name |
| 2319 |
// '@__spirv_BuiltInLocalInvocationId'. In such a case, we would want to |
| 2320 |
// create only a single global variable with this name. |
| 2321 |
if (GlobalVariable *GV = M->getGlobalVariable(BuiltinVarName)) |
| 2322 |
BV = GV; |
| 2323 |
else |
| 2324 |
BV = new GlobalVariable(*M, GVType, /*isConstant=*/true, |
| 2325 |
GlobalValue::ExternalLinkage, nullptr, |
| 2326 |
BuiltinVarName, 0, GlobalVariable::NotThreadLocal, |
| 2327 |
SPIRAS_Input); |
| 2328 |
for (auto *U : F.users()) { |
| 2329 |
auto *CI = dyn_cast<CallInst>(U); |
| 2330 |
assert(CI && "invalid instruction"); |
| 2331 |
IRBuilder<> Builder(CI); |
| 2332 |
Value *NewValue = Builder.CreateLoad(GVType, BV); |
| 2333 |
LLVM_DEBUG(dbgs() << "Transform: " << *CI << " => " << *NewValue << '\n'); |
| 2334 |
if (IsVec) { |
| 2335 |
auto *GVVecTy = cast<FixedVectorType>(GVType); |
| 2336 |
ConstantInt *Bound = Builder.getInt32(GVVecTy->getNumElements()); |
| 2337 |
// Create a select on the index first, to avoid undefined behaviour |
| 2338 |
// due to exceeding the vector size by the extractelement. |
| 2339 |
Value *IndexCmp = Builder.CreateICmpULT(CI->getArgOperand(0), Bound); |
| 2340 |
Constant *ZeroIndex = |
| 2341 |
ConstantInt::get(CI->getArgOperand(0)->getType(), 0); |
| 2342 |
Value *ExtractIndex = |
| 2343 |
Builder.CreateSelect(IndexCmp, CI->getArgOperand(0), ZeroIndex); |
| 2344 |
|
| 2345 |
// Extract from builtin variable. |
| 2346 |
NewValue = Builder.CreateExtractElement(NewValue, ExtractIndex); |
| 2347 |
|
| 2348 |
// Clamp to out-of-range value. |
| 2349 |
Constant *OutOfRangeVal = ConstantInt::get( |
| 2350 |
F.getReturnType(), getBuiltinOutOfRangeValue(BuiltinVarName)); |
| 2351 |
NewValue = Builder.CreateSelect(IndexCmp, NewValue, OutOfRangeVal); |
| 2352 |
LLVM_DEBUG(dbgs() << *NewValue << '\n'); |
| 2353 |
} |
| 2354 |
NewValue->takeName(CI); |
| 2355 |
CI->replaceAllUsesWith(NewValue); |
| 2356 |
ToRemove.push_back(CI); |
| 2357 |
} |
| 2358 |
ToRemove.push_back(&F); |
| 2359 |
} |
| 2360 |
for (auto *V : ToRemove) { |
| 2361 |
if (auto *I = dyn_cast<Instruction>(V)) |
| 2362 |
I->eraseFromParent(); |
| 2363 |
else if (auto *F = dyn_cast<Function>(V)) |
| 2364 |
F->eraseFromParent(); |
| 2365 |
else |
| 2366 |
llvm_unreachable("Unexpected value to remove!"); |
| 2367 |
} |
| 2368 |
return true; |
| 2369 |
} |
| 2370 |
|
| 2371 |
bool lowerBuiltins(SPIRVModule *BM, Module *M) { |
| 2372 |
auto Format = BM->getBuiltinFormat(); |
| 2373 |
if (Format == BuiltinFormat::Function && !lowerBuiltinVariablesToCalls(M)) |
| 2374 |
return false; |
| 2375 |
if (Format == BuiltinFormat::Global && !lowerBuiltinCallsToVariables(M)) |
| 2376 |
return false; |
| 2377 |
return true; |
| 2378 |
} |
| 2379 |
|
| 2380 |
bool postProcessBuiltinReturningStruct(Function *F) { |
| 2381 |
Module *M = F->getParent(); |
| 2382 |
LLVMContext *Context = &M->getContext(); |
| 2383 |
std::string Name = F->getName().str(); |
| 2384 |
F->setName(Name + ".old"); |
| 2385 |
SmallVector<Instruction *, 32> InstToRemove; |
| 2386 |
for (auto *U : F->users()) { |
| 2387 |
if (auto *CI = dyn_cast<CallInst>(U)) { |
| 2388 |
IRBuilder<> Builder(CI->getParent()); |
| 2389 |
Builder.SetInsertPoint(CI); |
| 2390 |
SmallVector<User *> Users(CI->users()); |
| 2391 |
Value *A = nullptr; |
| 2392 |
StoreInst *SI = nullptr; |
| 2393 |
for (auto *U : Users) { |
| 2394 |
if ((SI = dyn_cast<StoreInst>(U)) != nullptr) { |
| 2395 |
A = SI->getPointerOperand(); |
| 2396 |
InstToRemove.push_back(SI); |
| 2397 |
break; |
| 2398 |
} |
| 2399 |
} |
| 2400 |
if (!A) { |
| 2401 |
A = Builder.CreateAlloca(F->getReturnType()); |
| 2402 |
} |
| 2403 |
SmallVector<Type *> ArgTys; |
| 2404 |
getFunctionTypeParameterTypes(F->getFunctionType(), ArgTys); |
| 2405 |
ArgTys.insert(ArgTys.begin(), A->getType()); |
| 2406 |
auto *NewF = |
| 2407 |
getOrCreateFunction(M, Type::getVoidTy(*Context), ArgTys, Name); |
| 2408 |
auto SretAttr = Attribute::get(*Context, Attribute::AttrKind::StructRet, |
| 2409 |
F->getReturnType()); |
| 2410 |
NewF->addParamAttr(0, SretAttr); |
| 2411 |
NewF->setCallingConv(F->getCallingConv()); |
| 2412 |
auto Args = getArguments(CI); |
| 2413 |
Args.insert(Args.begin(), A); |
| 2414 |
CallInst *NewCI = Builder.CreateCall( |
| 2415 |
NewF, Args, NewF->getReturnType()->isVoidTy() ? "" : CI->getName()); |
| 2416 |
NewCI->addParamAttr(0, SretAttr); |
| 2417 |
NewCI->setCallingConv(CI->getCallingConv()); |
| 2418 |
SmallVector<User *, 32> UsersToReplace; |
| 2419 |
for (auto *U : Users) |
| 2420 |
if (U != SI) |
| 2421 |
UsersToReplace.push_back(U); |
| 2422 |
if (UsersToReplace.size() > 0) { |
| 2423 |
auto *LI = Builder.CreateLoad(F->getReturnType(), A); |
| 2424 |
for (auto *U : UsersToReplace) |
| 2425 |
U->replaceUsesOfWith(CI, LI); |
| 2426 |
} |
| 2427 |
InstToRemove.push_back(CI); |
| 2428 |
} |
| 2429 |
} |
| 2430 |
for (auto *Inst : InstToRemove) { |
| 2431 |
Inst->dropAllReferences(); |
| 2432 |
Inst->eraseFromParent(); |
| 2433 |
} |
| 2434 |
F->dropAllReferences(); |
| 2435 |
F->eraseFromParent(); |
| 2436 |
return true; |
| 2437 |
} |
| 2438 |
|
| 2439 |
bool postProcessBuiltinWithArrayArguments(Function *F, |
| 2440 |
StringRef DemangledName) { |
| 2441 |
LLVM_DEBUG(dbgs() << "[postProcessOCLBuiltinWithArrayArguments] " << *F |
| 2442 |
<< '\n'); |
| 2443 |
auto Attrs = F->getAttributes(); |
| 2444 |
auto Name = F->getName(); |
| 2445 |
mutateFunction( |
| 2446 |
F, |
| 2447 |
[=](CallInst *CI, std::vector<Value *> &Args) { |
| 2448 |
auto FBegin = CI->getFunction()->begin()->getFirstInsertionPt(); |
| 2449 |
for (auto &I : Args) { |
| 2450 |
auto *T = I->getType(); |
| 2451 |
if (!T->isArrayTy()) |
| 2452 |
continue; |
| 2453 |
auto *Alloca = new AllocaInst(T, 0, "", &(*FBegin)); |
| 2454 |
new StoreInst(I, Alloca, false, CI); |
| 2455 |
auto *Zero = |
| 2456 |
ConstantInt::getNullValue(Type::getInt32Ty(T->getContext())); |
| 2457 |
Value *Index[] = {Zero, Zero}; |
| 2458 |
I = GetElementPtrInst::CreateInBounds(T, Alloca, Index, "", CI); |
| 2459 |
} |
| 2460 |
return Name.str(); |
| 2461 |
}, |
| 2462 |
nullptr, &Attrs); |
| 2463 |
return true; |
| 2464 |
} |
| 2465 |
|
| 2466 |
bool postProcessBuiltinsReturningStruct(Module *M, bool IsCpp) { |
| 2467 |
StringRef DemangledName; |
| 2468 |
// postProcessBuiltinReturningStruct may remove some functions from the |
| 2469 |
// module, so use make_early_inc_range |
| 2470 |
for (auto &F : make_early_inc_range(M->functions())) { |
| 2471 |
if (F.hasName() && F.isDeclaration()) { |
| 2472 |
LLVM_DEBUG(dbgs() << "[postProcess sret] " << F << '\n'); |
| 2473 |
if (F.getReturnType()->isStructTy() && |
| 2474 |
oclIsBuiltin(F.getName(), DemangledName, IsCpp)) { |
| 2475 |
if (!postProcessBuiltinReturningStruct(&F)) |
| 2476 |
return false; |
| 2477 |
} |
| 2478 |
} |
| 2479 |
} |
| 2480 |
return true; |
| 2481 |
} |
| 2482 |
|
| 2483 |
bool postProcessBuiltinsWithArrayArguments(Module *M, bool IsCpp) { |
| 2484 |
StringRef DemangledName; |
| 2485 |
// postProcessBuiltinWithArrayArguments may remove some functions from the |
| 2486 |
// module, so use make_early_inc_range |
| 2487 |
for (auto &F : make_early_inc_range(M->functions())) { |
| 2488 |
if (F.hasName() && F.isDeclaration()) { |
| 2489 |
LLVM_DEBUG(dbgs() << "[postProcess array arg] " << F << '\n'); |
| 2490 |
if (hasArrayArg(&F) && oclIsBuiltin(F.getName(), DemangledName, IsCpp)) |
| 2491 |
if (!postProcessBuiltinWithArrayArguments(&F, DemangledName)) |
| 2492 |
return false; |
| 2493 |
} |
| 2494 |
} |
| 2495 |
return true; |
| 2496 |
} |
| 2497 |
|
| 2498 |
} // namespace SPIRV |
| 2499 |
|
| 2500 |
namespace { |
| 2501 |
class SPIRVFriendlyIRMangleInfo : public BuiltinFuncMangleInfo { |
| 2502 |
public: |
| 2503 |
SPIRVFriendlyIRMangleInfo(spv::Op OC, ArrayRef<Type *> ArgTys, |
| 2504 |
ArrayRef<SPIRVValue *> Ops) |
| 2505 |
: OC(OC), ArgTys(ArgTys), Ops(Ops) {} |
| 2506 |
|
| 2507 |
void init(StringRef UniqUnmangledName) override { |
| 2508 |
UnmangledName = UniqUnmangledName.str(); |
| 2509 |
switch (static_cast<unsigned>(OC)) { |
| 2510 |
case OpConvertUToF: |
| 2511 |
case OpUConvert: |
| 2512 |
case OpSatConvertUToS: |
| 2513 |
// Treat all arguments as unsigned |
| 2514 |
addUnsignedArg(-1); |
| 2515 |
break; |
| 2516 |
case OpSubgroupShuffleINTEL: |
| 2517 |
case OpSubgroupShuffleXorINTEL: |
| 2518 |
addUnsignedArg(1); |
| 2519 |
break; |
| 2520 |
case OpSubgroupShuffleDownINTEL: |
| 2521 |
case OpSubgroupShuffleUpINTEL: |
| 2522 |
addUnsignedArg(2); |
| 2523 |
break; |
| 2524 |
case OpSubgroupBlockWriteINTEL: |
| 2525 |
addUnsignedArg(0); |
| 2526 |
addUnsignedArg(1); |
| 2527 |
break; |
| 2528 |
case OpSubgroupImageBlockWriteINTEL: |
| 2529 |
addUnsignedArg(2); |
| 2530 |
break; |
| 2531 |
case OpSubgroupBlockReadINTEL: |
| 2532 |
setArgAttr(0, SPIR::ATTR_CONST); |
| 2533 |
addUnsignedArg(0); |
| 2534 |
break; |
| 2535 |
case OpAtomicUMax: |
| 2536 |
case OpAtomicUMin: |
| 2537 |
addUnsignedArg(0); |
| 2538 |
addUnsignedArg(3); |
| 2539 |
break; |
| 2540 |
case OpGroupUMax: |
| 2541 |
case OpGroupUMin: |
| 2542 |
case OpGroupNonUniformBroadcast: |
| 2543 |
case OpGroupNonUniformBallotBitCount: |
| 2544 |
case OpGroupNonUniformShuffle: |
| 2545 |
case OpGroupNonUniformShuffleXor: |
| 2546 |
case OpGroupNonUniformShuffleUp: |
| 2547 |
case OpGroupNonUniformShuffleDown: |
| 2548 |
addUnsignedArg(2); |
| 2549 |
break; |
| 2550 |
case OpGroupNonUniformRotateKHR: |
| 2551 |
if (ArgTys.size() == 4) |
| 2552 |
addUnsignedArg(3); |
| 2553 |
break; |
| 2554 |
case OpGroupNonUniformInverseBallot: |
| 2555 |
case OpGroupNonUniformBallotFindLSB: |
| 2556 |
case OpGroupNonUniformBallotFindMSB: |
| 2557 |
addUnsignedArg(1); |
| 2558 |
break; |
| 2559 |
case OpBitFieldSExtract: |
| 2560 |
case OpGroupNonUniformBallotBitExtract: |
| 2561 |
addUnsignedArg(1); |
| 2562 |
addUnsignedArg(2); |
| 2563 |
break; |
| 2564 |
case OpGroupNonUniformIAdd: |
| 2565 |
case OpGroupNonUniformFAdd: |
| 2566 |
case OpGroupNonUniformIMul: |
| 2567 |
case OpGroupNonUniformFMul: |
| 2568 |
case OpGroupNonUniformSMin: |
| 2569 |
case OpGroupNonUniformFMin: |
| 2570 |
case OpGroupNonUniformSMax: |
| 2571 |
case OpGroupNonUniformFMax: |
| 2572 |
case OpGroupNonUniformBitwiseAnd: |
| 2573 |
case OpGroupNonUniformBitwiseOr: |
| 2574 |
case OpGroupNonUniformBitwiseXor: |
| 2575 |
case OpGroupNonUniformLogicalAnd: |
| 2576 |
case OpGroupNonUniformLogicalOr: |
| 2577 |
case OpGroupNonUniformLogicalXor: |
| 2578 |
addUnsignedArg(3); |
| 2579 |
break; |
| 2580 |
case OpBitFieldInsert: |
| 2581 |
case OpGroupNonUniformUMax: |
| 2582 |
case OpGroupNonUniformUMin: |
| 2583 |
addUnsignedArg(2); |
| 2584 |
addUnsignedArg(3); |
| 2585 |
break; |
| 2586 |
case OpEnqueueMarker: |
| 2587 |
addUnsignedArg(1); |
| 2588 |
break; |
| 2589 |
case OpSubgroupAvcBmeInitializeINTEL: |
| 2590 |
addUnsignedArgs(0, 7); |
| 2591 |
break; |
| 2592 |
case OpSubgroupAvcFmeInitializeINTEL: |
| 2593 |
case OpSubgroupAvcSicConfigureIpeLumaINTEL: |
| 2594 |
addUnsignedArgs(0, 6); |
| 2595 |
break; |
| 2596 |
case OpSubgroupAvcImeAdjustRefOffsetINTEL: |
| 2597 |
addUnsignedArgs(1, 3); |
| 2598 |
break; |
| 2599 |
case OpSubgroupAvcImeGetBorderReachedINTEL: |
| 2600 |
case OpSubgroupAvcImeRefWindowSizeINTEL: |
| 2601 |
case OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL: |
| 2602 |
case OpSubgroupAvcImeSetMaxMotionVectorCountINTEL: |
| 2603 |
case OpSubgroupAvcImeSetWeightedSadINTEL: |
| 2604 |
case OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL: |
| 2605 |
case OpSubgroupAvcMceSetInterDirectionPenaltyINTEL: |
| 2606 |
case OpSubgroupAvcMceSetInterShapePenaltyINTEL: |
| 2607 |
case OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL: |
| 2608 |
case OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL: |
| 2609 |
case OpSubgroupAvcSicInitializeINTEL: |
| 2610 |
case OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL: |
| 2611 |
case OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL: |
| 2612 |
case OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL: |
| 2613 |
case OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL: |
| 2614 |
addUnsignedArg(0); |
| 2615 |
break; |
| 2616 |
case OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL: |
| 2617 |
case OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL: |
| 2618 |
case OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL: |
| 2619 |
case OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL: |
| 2620 |
case OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL: |
| 2621 |
case OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL: |
| 2622 |
case OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL: |
| 2623 |
addUnsignedArgs(1, 2); |
| 2624 |
break; |
| 2625 |
case OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL: |
| 2626 |
case OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL: |
| 2627 |
case OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL: |
| 2628 |
case OpSubgroupAvcImeSetSingleReferenceINTEL: |
| 2629 |
addUnsignedArg(1); |
| 2630 |
break; |
| 2631 |
case OpBitFieldUExtract: |
| 2632 |
case OpSubgroupAvcImeInitializeINTEL: |
| 2633 |
case OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL: |
| 2634 |
case OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL: |
| 2635 |
addUnsignedArgs(0, 2); |
| 2636 |
break; |
| 2637 |
case OpSubgroupAvcImeSetDualReferenceINTEL: |
| 2638 |
addUnsignedArg(2); |
| 2639 |
break; |
| 2640 |
case OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL: |
| 2641 |
case OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL: |
| 2642 |
case OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL: |
| 2643 |
case OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL: |
| 2644 |
case OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL: |
| 2645 |
case OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL: |
| 2646 |
case OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL: |
| 2647 |
case OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL: |
| 2648 |
case OpSubgroupAvcSicGetMotionVectorMaskINTEL: |
| 2649 |
addUnsignedArgs(0, 1); |
| 2650 |
break; |
| 2651 |
case OpSubgroupAvcSicConfigureIpeLumaChromaINTEL: |
| 2652 |
addUnsignedArgs(0, 9); |
| 2653 |
break; |
| 2654 |
case OpSubgroupAvcSicConfigureSkcINTEL: |
| 2655 |
addUnsignedArgs(0, 4); |
| 2656 |
break; |
| 2657 |
case OpUDotKHR: |
| 2658 |
case OpUDotAccSatKHR: |
| 2659 |
addUnsignedArg(-1); |
| 2660 |
break; |
| 2661 |
case OpSUDotKHR: |
| 2662 |
case OpSUDotAccSatKHR: |
| 2663 |
addUnsignedArg(1); |
| 2664 |
break; |
| 2665 |
case OpImageWrite: { |
| 2666 |
size_t Idx = getImageOperandsIndex(OC); |
| 2667 |
if (Ops.size() > Idx) { |
| 2668 |
auto ImOp = static_cast<SPIRVConstant *>(Ops[Idx])->getZExtIntValue(); |
| 2669 |
if (ImOp & ImageOperandsMask::ImageOperandsZeroExtendMask) |
| 2670 |
addUnsignedArg(2); |
| 2671 |
} |
| 2672 |
break; |
| 2673 |
} |
| 2674 |
case internal::OpConvertHandleToImageINTEL: |
| 2675 |
case internal::OpConvertHandleToSamplerINTEL: |
| 2676 |
case internal::OpConvertHandleToSampledImageINTEL: |
| 2677 |
addUnsignedArg(0); |
| 2678 |
break; |
| 2679 |
default:; |
| 2680 |
// No special handling is needed |
| 2681 |
} |
| 2682 |
} |
| 2683 |
|
| 2684 |
private: |
| 2685 |
spv::Op OC; |
| 2686 |
ArrayRef<Type *> ArgTys; |
| 2687 |
ArrayRef<SPIRVValue *> Ops; |
| 2688 |
}; |
| 2689 |
class OpenCLStdToSPIRVFriendlyIRMangleInfo : public BuiltinFuncMangleInfo { |
| 2690 |
public: |
| 2691 |
OpenCLStdToSPIRVFriendlyIRMangleInfo(OCLExtOpKind ExtOpId, |
| 2692 |
ArrayRef<Type *> ArgTys, Type *RetTy) |
| 2693 |
: ExtOpId(ExtOpId), ArgTys(ArgTys) { |
| 2694 |
|
| 2695 |
std::string Postfix = ""; |
| 2696 |
if (needRetTypePostfix()) |
| 2697 |
Postfix = kSPIRVPostfix::Divider + getPostfixForReturnType(RetTy, true); |
| 2698 |
|
| 2699 |
UnmangledName = getSPIRVExtFuncName(SPIRVEIS_OpenCL, ExtOpId, Postfix); |
| 2700 |
} |
| 2701 |
|
| 2702 |
bool needRetTypePostfix() { |
| 2703 |
switch (ExtOpId) { |
| 2704 |
case OpenCLLIB::Vload_half: |
| 2705 |
case OpenCLLIB::Vload_halfn: |
| 2706 |
case OpenCLLIB::Vloada_halfn: |
| 2707 |
case OpenCLLIB::Vloadn: |
| 2708 |
return true; |
| 2709 |
default: |
| 2710 |
return false; |
| 2711 |
} |
| 2712 |
} |
| 2713 |
|
| 2714 |
void init(StringRef) override { |
| 2715 |
switch (ExtOpId) { |
| 2716 |
case OpenCLLIB::UAbs: |
| 2717 |
case OpenCLLIB::UAbs_diff: |
| 2718 |
case OpenCLLIB::UAdd_sat: |
| 2719 |
case OpenCLLIB::UHadd: |
| 2720 |
case OpenCLLIB::URhadd: |
| 2721 |
case OpenCLLIB::UClamp: |
| 2722 |
case OpenCLLIB::UMad_hi: |
| 2723 |
case OpenCLLIB::UMad_sat: |
| 2724 |
case OpenCLLIB::UMax: |
| 2725 |
case OpenCLLIB::UMin: |
| 2726 |
case OpenCLLIB::UMul_hi: |
| 2727 |
case OpenCLLIB::USub_sat: |
| 2728 |
case OpenCLLIB::U_Upsample: |
| 2729 |
case OpenCLLIB::UMad24: |
| 2730 |
case OpenCLLIB::UMul24: |
| 2731 |
// Treat all arguments as unsigned |
| 2732 |
addUnsignedArg(-1); |
| 2733 |
break; |
| 2734 |
case OpenCLLIB::S_Upsample: |
| 2735 |
addUnsignedArg(1); |
| 2736 |
break; |
| 2737 |
default:; |
| 2738 |
// No special handling is needed |
| 2739 |
} |
| 2740 |
} |
| 2741 |
|
| 2742 |
private: |
| 2743 |
OCLExtOpKind ExtOpId; |
| 2744 |
ArrayRef<Type *> ArgTys; |
| 2745 |
}; |
| 2746 |
} // namespace |
| 2747 |
|
| 2748 |
namespace SPIRV { |
| 2749 |
std::string getSPIRVFriendlyIRFunctionName(OCLExtOpKind ExtOpId, |
| 2750 |
ArrayRef<Type *> ArgTys, |
| 2751 |
Type *RetTy) { |
| 2752 |
OpenCLStdToSPIRVFriendlyIRMangleInfo MangleInfo(ExtOpId, ArgTys, RetTy); |
| 2753 |
return mangleBuiltin(MangleInfo.getUnmangledName(), ArgTys, &MangleInfo); |
| 2754 |
} |
| 2755 |
|
| 2756 |
std::string getSPIRVFriendlyIRFunctionName(const std::string &UniqName, |
| 2757 |
spv::Op OC, ArrayRef<Type *> ArgTys, |
| 2758 |
ArrayRef<SPIRVValue *> Ops) { |
| 2759 |
SPIRVFriendlyIRMangleInfo MangleInfo(OC, ArgTys, Ops); |
| 2760 |
return mangleBuiltin(UniqName, ArgTys, &MangleInfo); |
| 2761 |
} |
| 2762 |
|
| 2763 |
template <typename T> |
| 2764 |
MetadataAsValue *map2MDString(LLVMContext &C, SPIRVValue *V) { |
| 2765 |
if (V->getOpCode() != OpConstant) |
| 2766 |
return nullptr; |
| 2767 |
uint64_t Const = static_cast<SPIRVConstant *>(V)->getZExtIntValue(); |
| 2768 |
std::string Str = SPIRVMap<T, std::string>::map(static_cast<T>(Const)); |
| 2769 |
return MetadataAsValue::get(C, MDString::get(C, Str)); |
| 2770 |
} |
| 2771 |
|
| 2772 |
} // namespace SPIRV |