RemoveNonkernelsPass.cpp revision 7974fc03e11f3a8dd40f794f3b33b4889483090c
1/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "RemoveNonkernelsPass.h"
18
19#include "bcinfo/MetadataExtractor.h"
20
21#include "llvm/ADT/StringSet.h"
22#include "llvm/IR/Attributes.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/PassManager.h"
26#include "llvm/Pass.h"
27#include "llvm/Support/Debug.h"
28
29#define DEBUG_TYPE "rs2spirv-remove"
30
31using namespace llvm;
32
33namespace rs2spirv {
34
35namespace {
36
37class RemoveNonkernelsPass : public ModulePass {
38  bcinfo::MetadataExtractor &ME;
39
40public:
41  static char ID;
42  explicit RemoveNonkernelsPass(bcinfo::MetadataExtractor &Extractor)
43      : ModulePass(ID), ME(Extractor) {}
44
45  const char *getPassName() const override { return "RemoveNonkernelsPass"; }
46
47  bool runOnModule(Module &M) override {
48    DEBUG(dbgs() << "RemoveNonkernelsPass\n");
49    DEBUG(M.dump());
50
51    const size_t RSKernelNum = ME.getExportForEachSignatureCount();
52    const char **RSKernelNames = ME.getExportForEachNameList();
53    if (RSKernelNum == 0)
54      DEBUG(dbgs() << "RemoveNonkernelsPass detected no kernel\n");
55
56    StringSet<> KNames;
57    for (size_t i = 0; i < RSKernelNum; ++i)
58      KNames.insert(RSKernelNames[i]);
59
60    std::vector<Function *> Functions;
61    for (auto &F : M.functions()) {
62      Functions.push_back(&F);
63    }
64
65    for (auto &F : Functions) {
66      if (F->isDeclaration())
67        continue;
68
69      const StringRef FName = F->getName();
70
71      if (KNames.count(FName) != 0)
72        continue; // Skip kernels.
73
74      F->replaceAllUsesWith(UndefValue::get((Type *)F->getType()));
75      F->eraseFromParent();
76
77      DEBUG(dbgs() << "Removed:\t" << FName << '\n');
78    }
79
80    // Return true, as the pass modifies module.
81    DEBUG(M.dump());
82    DEBUG(dbgs() << "Done removal\n");
83
84    return true;
85  }
86};
87} // namespace
88
89char RemoveNonkernelsPass::ID = 0;
90
91ModulePass *createRemoveNonkernelsPass(bcinfo::MetadataExtractor &ME) {
92  return new RemoveNonkernelsPass(ME);
93}
94
95} // namespace rs2spirv
96