Skip to content

Commit

Permalink
Add a helper for type-aware mutateCallInst replacement. (intel#1611)
Browse files Browse the repository at this point in the history
Opaque pointers requires us to keep more careful track of the pointee types of the builtin methods. While these are discoverable via demangling, the existing interface of mutateCallInst* does not provide easy ways to maintain these types during remapping of OpenCL builtins to SPIR-V builtins.

This patch adds a BuiltinCallMutator that keeps track not only of the pointer element types discovered by demangling, but also of the LLVM attributes the arguments originally had, even as arguments are inserted or deleted for OpenCL<->SPIR-V builtin conversions. Additionally, the interface is intended to be more forgiving of the varieties of lambdas needed to do the conversions: for example, there is no need for different entry points to indicate a type-aware mapping, or even to indicate a function whose return type changes.

It is intended that all of the existing calls to mutateCallInst be replaced with this new interface, so as to be able to eliminate the getPointerElementType call in the existing implementation of that function. However, the actual migration of the calls will be done in future patches to keep the maximum size of patches relatively small.
  • Loading branch information
jcranmer-intel authored and bader committed Sep 19, 2022
1 parent c294993 commit f2a1b67
Show file tree
Hide file tree
Showing 10 changed files with 524 additions and 19 deletions.
1 change: 1 addition & 0 deletions llvm-spirv/lib/SPIRV/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ set(SRC_LIST
OCLTypeToSPIRV.cpp
OCLUtil.cpp
VectorComputeUtil.cpp
SPIRVBuiltinHelper.cpp
SPIRVLowerBitCastToNonStandardType.cpp
SPIRVLowerBool.cpp
SPIRVLowerConstExpr.cpp
Expand Down
4 changes: 2 additions & 2 deletions llvm-spirv/lib/SPIRV/OCLToSPIRV.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ void OCLToSPIRVBase::transVecLoadStoreName(std::string &DemangledName,
char OCLToSPIRVLegacy::ID = 0;

bool OCLToSPIRVBase::runOCLToSPIRV(Module &Module) {
M = &Module;
initialize(Module);
Ctx = &M->getContext();
auto Src = getSPIRVSource(&Module);
// This is a pre-processing pass, which transform LLVM IR module to a more
Expand Down Expand Up @@ -1581,7 +1581,7 @@ void OCLToSPIRVBase::visitCallKernelQuery(CallInst *CI,
auto *BlockF = cast<Function>(getUnderlyingObject(BlockFVal));

AttributeList Attrs = CI->getCalledFunction()->getAttributes();
mutateCallInst(
::mutateCallInst(
M, CI,
[=](CallInst *CI, std::vector<Value *> &Args) {
Value *Param = *Args.rbegin();
Expand Down
7 changes: 4 additions & 3 deletions llvm-spirv/lib/SPIRV/OCLToSPIRV.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#define SPIRV_OCLTOSPIRV_H

#include "OCLUtil.h"
#include "SPIRVBuiltinHelper.h"

#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/PassManager.h"
Expand All @@ -50,10 +51,11 @@ namespace SPIRV {

class OCLTypeToSPIRVBase;

class OCLToSPIRVBase : public InstVisitor<OCLToSPIRVBase> {
class OCLToSPIRVBase : public InstVisitor<OCLToSPIRVBase>, BuiltinCallHelper {
public:
OCLToSPIRVBase()
: M(nullptr), Ctx(nullptr), CLVer(0), OCLTypeToSPIRVPtr(nullptr) {}
: BuiltinCallHelper(ManglingRules::SPIRV), Ctx(nullptr), CLVer(0),
OCLTypeToSPIRVPtr(nullptr) {}
virtual ~OCLToSPIRVBase() {}
bool runOCLToSPIRV(Module &M);

Expand Down Expand Up @@ -264,7 +266,6 @@ class OCLToSPIRVBase : public InstVisitor<OCLToSPIRVBase> {
OCLTypeToSPIRVBase *getOCLTypeToSPIRV() { return OCLTypeToSPIRVPtr; }

private:
Module *M;
LLVMContext *Ctx;
unsigned CLVer; /// OpenCL version as major*10+minor
std::set<Value *> ValuesToDelete;
Expand Down
15 changes: 7 additions & 8 deletions llvm-spirv/lib/SPIRV/OCLUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -979,9 +979,7 @@ static FunctionType *getBlockInvokeTy(Function *F, unsigned BlockIdx) {
class OCLBuiltinFuncMangleInfo : public SPIRV::BuiltinFuncMangleInfo {
public:
OCLBuiltinFuncMangleInfo(Function *F) : F(F) {}
OCLBuiltinFuncMangleInfo(ArrayRef<Type *> ArgTypes)
: ArgTypes(ArgTypes.vec()) {}
Type *getArgTy(unsigned I) { return F->getFunctionType()->getParamType(I); }
OCLBuiltinFuncMangleInfo() = default;
void init(StringRef UniqName) override {
// Make a local copy as we will modify the string in init function
std::string TempStorage = UniqName.str();
Expand Down Expand Up @@ -1305,10 +1303,7 @@ class OCLBuiltinFuncMangleInfo : public SPIRV::BuiltinFuncMangleInfo {
}
// Auxiliarry information, it is expected that it is relevant at the moment
// the init method is called.
Function *F; // SPIRV decorated function
// TODO: ArgTypes argument should get removed once all SPV-IR related issues
// are resolved
std::vector<Type *> ArgTypes; // Arguments of OCL builtin
Function *F; // SPIRV decorated function
};

CallInst *mutateCallInstOCL(
Expand All @@ -1330,6 +1325,10 @@ Instruction *mutateCallInstOCL(
TakeFuncName);
}

std::unique_ptr<SPIRV::BuiltinFuncMangleInfo> makeMangler(Function &F) {
return std::make_unique<OCLBuiltinFuncMangleInfo>(&F);
}

static StringRef getStructName(Type *Ty) {
if (auto *STy = dyn_cast<StructType>(Ty))
return STy->isLiteral() ? "" : Ty->getStructName();
Expand Down Expand Up @@ -1603,6 +1602,6 @@ Value *SPIRV::transSPIRVMemorySemanticsIntoOCLMemFenceFlags(
void llvm::mangleOpenClBuiltin(const std::string &UniqName,
ArrayRef<Type *> ArgTypes,
std::string &MangledName) {
OCLUtil::OCLBuiltinFuncMangleInfo BtnInfo(ArgTypes);
OCLUtil::OCLBuiltinFuncMangleInfo BtnInfo;
MangledName = SPIRV::mangleBuiltin(UniqName, ArgTypes, &BtnInfo);
}
6 changes: 6 additions & 0 deletions llvm-spirv/lib/SPIRV/OCLUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ using namespace SPIRV;
using namespace llvm;
using namespace spv;

namespace SPIRV {
class BuiltinCallMutator;
} // namespace SPIRV

namespace OCLUtil {

///////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -520,6 +524,8 @@ std::string getIntelSubgroupBlockDataPostfix(unsigned ElementBitSize,

void insertImageNameAccessQualifier(SPIRVAccessQualifierKind Acc,
std::string &Name);

std::unique_ptr<SPIRV::BuiltinFuncMangleInfo> makeMangler(Function &F);
} // namespace OCLUtil

using namespace OCLUtil;
Expand Down
213 changes: 213 additions & 0 deletions llvm-spirv/lib/SPIRV/SPIRVBuiltinHelper.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
//===- SPIRVBuiltinHelper.cpp - Helpers for managing calls to builtins ----===//
//
// The LLVM/SPIR-V Translator
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
// Copyright (c) 2022 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the documentation
// and/or other materials provided with the distribution.
// Neither the names of The Khronos Group, nor the names of its
// contributors may be used to endorse or promote products derived from this
// Software without specific prior written permission.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
// THE SOFTWARE.
//
//===----------------------------------------------------------------------===//
//
// This file implements helper functions for adding calls to OpenCL or SPIR-V
// builtin functions, or for rewriting calls to one into calls to the other.
//
//===----------------------------------------------------------------------===//

#include "SPIRVBuiltinHelper.h"

#include "OCLUtil.h"
#include "SPIRVInternal.h"

using namespace llvm;
using namespace SPIRV;

static std::unique_ptr<BuiltinFuncMangleInfo> makeMangler(CallBase *CB,
ManglingRules Rules) {
switch (Rules) {
case ManglingRules::None:
return nullptr;
case ManglingRules::SPIRV:
return std::make_unique<BuiltinFuncMangleInfo>();
case ManglingRules::OpenCL:
return OCLUtil::makeMangler(*CB->getCalledFunction());
}
llvm_unreachable("Unknown mangling rules to make a name mangler");
}

BuiltinCallMutator::BuiltinCallMutator(
CallInst *CI, std::string FuncName, ManglingRules Rules,
std::function<std::string(StringRef)> NameMapFn)
: CI(CI), FuncName(FuncName),
Attrs(CI->getCalledFunction()->getAttributes()), ReturnTy(CI->getType()),
Args(CI->args()), Rules(Rules), Builder(CI) {
getParameterTypes(CI->getCalledFunction(), PointerTypes,
std::move(NameMapFn));
PointerTypes.resize(Args.size(), nullptr);
}

BuiltinCallMutator::BuiltinCallMutator(BuiltinCallMutator &&Other)
: CI(Other.CI), FuncName(std::move(Other.FuncName)),
MutateRet(std::move(Other.MutateRet)), Attrs(Other.Attrs),
ReturnTy(Other.ReturnTy), Args(std::move(Other.Args)),
PointerTypes(std::move(Other.PointerTypes)),
Rules(std::move(Other.Rules)), Builder(CI) {
// Clear the other's CI instance so that it knows not to construct the actual
// call.
Other.CI = nullptr;
}

Value *BuiltinCallMutator::doConversion() {
assert(CI && "Need to have a call instruction to do the conversion");
auto Mangler = makeMangler(CI, Rules);
for (unsigned I = 0; I < Args.size(); I++) {
Mangler->getTypeMangleInfo(I).PointerTy = PointerTypes[I];
}
assert(Attrs.getNumAttrSets() <= Args.size() + 2 && "Too many attributes?");
CallInst *NewCall =
Builder.Insert(addCallInst(CI->getModule(), FuncName, ReturnTy, Args,
&Attrs, nullptr, Mangler.get()));
Value *Result = MutateRet ? MutateRet(Builder, NewCall) : NewCall;
Result->takeName(CI);
if (!CI->getType()->isVoidTy())
CI->replaceAllUsesWith(Result);
CI->dropAllReferences();
CI->eraseFromParent();
CI = nullptr;
return Result;
}

BuiltinCallMutator &BuiltinCallMutator::setArgs(ArrayRef<Value *> NewArgs) {
// Retain only the function attributes, not any parameter attributes.
Attrs = AttributeList::get(CI->getContext(), Attrs.getFnAttrs(),
Attrs.getRetAttrs(), {});
Args.clear();
PointerTypes.clear();
for (Value *Arg : NewArgs) {
assert(!Arg->getType()->isPointerTy() &&
"Cannot use this signature with pointer types");
Args.push_back(Arg);
PointerTypes.emplace_back();
}
return *this;
}

// This is a helper method to handle splicing of the attribute lists, as
// llvm::AttributeList doesn't have any helper methods for this sort of design.
// (It's designed to be manually built-up, not adjusted to add/remove
// arguments on the fly).
static void moveAttributes(LLVMContext &Ctx, AttributeList &Attrs,
unsigned Start, unsigned Len, unsigned Dest) {
SmallVector<std::pair<unsigned, AttributeSet>, 6> NewAttrs;
for (unsigned Index : Attrs.indexes()) {
AttributeSet AttrSet = Attrs.getAttributes(Index);
if (!AttrSet.hasAttributes())
continue;

// If the attribute is a parameter index, check to see how its index should
// be adjusted.
if (Index > AttributeList::FirstArgIndex) {
unsigned ParamIndex = Index - AttributeList::FirstArgIndex;
if (ParamIndex >= Start && ParamIndex < Start + Len)
// A parameter in this range needs to have its index adjusted to its
// destination location.
Index += Dest - Start;
else if (ParamIndex >= Dest && ParamIndex < Dest + Len)
// This parameter will be overwritten by one of the moved parameters, so
// omit it entirely.
continue;
}

// The array is usually going to be sorted, but because of the above
// adjustment, we might end up out of order. This logic ensures that the
// array always remains in sorted order.
std::pair<unsigned, AttributeSet> ToInsert(Index, AttrSet);
NewAttrs.insert(llvm::lower_bound(NewAttrs, ToInsert, llvm::less_first()),
ToInsert);
}
Attrs = AttributeList::get(Ctx, NewAttrs);
}

// Convert a ValueTypePair to a TypedPointerType for storing in the PointerTypes
// array.
static TypedPointerType *toTPT(BuiltinCallMutator::ValueTypePair Pair) {
if (!Pair.second)
return nullptr;
unsigned AS = 0;
if (auto *TPT = dyn_cast<TypedPointerType>(Pair.first->getType()))
AS = TPT->getAddressSpace();
else if (isa<PointerType>(Pair.first->getType()))
AS = Pair.first->getType()->getPointerAddressSpace();
return TypedPointerType::get(Pair.second, AS);
}

BuiltinCallMutator &BuiltinCallMutator::insertArg(unsigned Index,
ValueTypePair Arg) {
Args.insert(Args.begin() + Index, Arg.first);
PointerTypes.insert(PointerTypes.begin() + Index, toTPT(Arg));
moveAttributes(CI->getContext(), Attrs, Index, Args.size() - Index,
Index + 1);
return *this;
}

BuiltinCallMutator &BuiltinCallMutator::replaceArg(unsigned Index,
ValueTypePair Arg) {
Args[Index] = Arg.first;
PointerTypes[Index] = toTPT(Arg);
Attrs = Attrs.removeParamAttributes(CI->getContext(), Index);
return *this;
}

BuiltinCallMutator &BuiltinCallMutator::removeArg(unsigned Index) {
// If the argument being dropped is the last one, there is nothing to move, so
// just remove the attributes.
if (Index == Args.size() - 1)
Attrs = Attrs.removeParamAttributes(CI->getContext(), Index);
else
moveAttributes(CI->getContext(), Attrs, Index + 1, Args.size() - Index - 1,
Index);
Args.erase(Args.begin() + Index);
PointerTypes.erase(PointerTypes.begin() + Index);
return *this;
}

BuiltinCallMutator &
BuiltinCallMutator::changeReturnType(Type *NewReturnTy,
MutateRetFuncTy MutateFunc) {
ReturnTy = NewReturnTy;
MutateRet = std::move(MutateFunc);
return *this;
}

BuiltinCallMutator BuiltinCallHelper::mutateCallInst(CallInst *CI,
spv::Op Opcode) {
return mutateCallInst(CI, getSPIRVFuncName(Opcode));
}

BuiltinCallMutator BuiltinCallHelper::mutateCallInst(CallInst *CI,
std::string FuncName) {
return BuiltinCallMutator(CI, std::move(FuncName), Rules, NameMapFn);
}
Loading

0 comments on commit f2a1b67

Please sign in to comment.