summaryrefslogtreecommitdiffstats
path: root/mlir/lib/Conversion/GPUToCUDA/GenerateCubinAccessors.cpp
blob: b819de2471e70e329a8b2edbc7d8c1bac9278a52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//===- GenerateCubinAccessors.cpp - MLIR GPU lowering passes --------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
//
// This file implements a pass to generate LLVMIR functions that return the
// data stored in nvvm.cubin char* blob.
//
//===----------------------------------------------------------------------===//

#include "mlir/Dialect/GPU/GPUDialect.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Identifier.h"
#include "mlir/IR/Module.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/LLVMIR/LLVMDialect.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassRegistry.h"

#include "llvm/ADT/STLExtras.h"

namespace mlir {
namespace {

// TODO(herhut): Move to shared location.
constexpr const char *kCubinAnnotation = "nvvm.cubin";
constexpr const char *kCubinGetterAnnotation = "nvvm.cubingetter";
constexpr const char *kCubinGetterSuffix = "_cubin";
constexpr const char *kCubinStorageSuffix = "_cubin_cst";

/// A pass generating global strings and getter functions for all cubin blobs
/// annotated on functions via the nvvm.cubin attribute.
class GpuGenerateCubinAccessorsPass
    : public ModulePass<GpuGenerateCubinAccessorsPass> {
private:
  LLVM::LLVMType getIndexType() {
    unsigned bits =
        llvmDialect->getLLVMModule().getDataLayout().getPointerSizeInBits();
    return LLVM::LLVMType::getIntNTy(llvmDialect, bits);
  }

  // Inserts a global constant string containing `blob` into the parent module
  // of `orig` and generates the function that returns the address of the first
  // character of this string.
  // TODO(herhut): consider fusing this pass with launch-func-to-cuda.
  void generate(FuncOp orig, StringAttr blob) {
    Location loc = orig.getLoc();
    SmallString<128> nameBuffer(orig.getName());
    auto module = orig.getParentOfType<ModuleOp>();
    assert(module && "function must belong to a module");

    // Create a global at the top of the module.
    OpBuilder moduleBuilder(module.getBody(), module.getBody()->begin());
    auto type = LLVM::LLVMType::getArrayTy(
        LLVM::LLVMType::getInt8Ty(llvmDialect), blob.getValue().size());
    nameBuffer.append(kCubinStorageSuffix);
    auto cubinGlobalString = moduleBuilder.create<LLVM::GlobalOp>(
        loc, type, /*isConstant=*/true, StringRef(nameBuffer), blob);

    // Insert the getter function just after the original function.
    moduleBuilder.setInsertionPoint(orig.getOperation()->getNextNode());
    auto getterType = moduleBuilder.getFunctionType(
        llvm::None, LLVM::LLVMType::getInt8PtrTy(llvmDialect));
    // Drop the storage suffix before appending the getter suffix.
    nameBuffer.resize(orig.getName().size());
    nameBuffer.append(kCubinGetterSuffix);
    auto result = moduleBuilder.create<FuncOp>(
        loc, StringRef(nameBuffer), getterType, ArrayRef<NamedAttribute>());
    Block *entryBlock = result.addEntryBlock();

    // Obtain the address of the first character of the global string containing
    // the cubin and return from the getter (addressof will return [? x i8]*).
    OpBuilder builder(entryBlock);
    Value *cubinGlobalStringPtr =
        builder.create<LLVM::AddressOfOp>(loc, cubinGlobalString);
    Value *cst0 = builder.create<LLVM::ConstantOp>(
        loc, getIndexType(), builder.getIntegerAttr(builder.getIndexType(), 0));
    Value *startPtr = builder.create<LLVM::GEPOp>(
        loc, LLVM::LLVMType::getInt8PtrTy(llvmDialect), cubinGlobalStringPtr,
        ArrayRef<Value *>({cst0, cst0}));
    builder.create<LLVM::ReturnOp>(loc, startPtr);

    // Store the name of the getter on the function for easier lookup.
    orig.setAttr(kCubinGetterAnnotation, builder.getSymbolRefAttr(result));
  }

public:
  // Perform the conversion on the module.  This may insert globals, so it
  // cannot be done on multiple functions in parallel.
  void runOnModule() override {
    llvmDialect =
        getModule().getContext()->getRegisteredDialect<LLVM::LLVMDialect>();

    for (auto func : getModule().getOps<FuncOp>()) {
      StringAttr cubinBlob = func.getAttrOfType<StringAttr>(kCubinAnnotation);
      if (!cubinBlob)
        continue;
      generate(func, cubinBlob);
    }
  }

private:
  LLVM::LLVMDialect *llvmDialect;
};

} // anonymous namespace

std::unique_ptr<ModulePassBase> createGenerateCubinAccessorPass() {
  return std::make_unique<GpuGenerateCubinAccessorsPass>();
}

static PassRegistration<GpuGenerateCubinAccessorsPass>
    pass("generate-cubin-accessors",
         "Generate LLVMIR functions that give access to cubin data");

} // namespace mlir
OpenPOWER on IntegriCloud