RemoveNonkernelsPass.cpp revision b83f1f4d77c7624b9e8dc11beec8f796ff841918
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 "llvm/ADT/StringSet.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Pass.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_ostream.h"
25
26#include "bcinfo/MetadataExtractor.h"
27
28#define DEBUG_TYPE "rs2spirv-remove"
29
30using namespace llvm;
31
32namespace rs2spirv {
33
34namespace {
35
36class RemoveNonkernelsPass : public ModulePass {
37  bcinfo::MetadataExtractor &ME;
38
39public:
40  static char ID;
41  explicit RemoveNonkernelsPass(bcinfo::MetadataExtractor &Extractor)
42      : ModulePass(ID), ME(Extractor) {}
43
44  const char *getPassName() const override { return "RemoveNonkernelsPass"; }
45
46  bool runOnModule(Module &M) override {
47    DEBUG(dbgs() << "RemoveNonkernelsPass\n");
48    DEBUG(M.dump());
49
50    const size_t RSKernelNum = ME.getExportForEachSignatureCount();
51    const char **RSKernelNames = ME.getExportForEachNameList();
52    if (RSKernelNum == 0)
53      DEBUG(dbgs() << "RemoveNonkernelsPass detected no kernel\n");
54
55    StringSet<> KNames;
56    for (size_t i = 0; i < RSKernelNum; ++i)
57      KNames.insert(RSKernelNames[i]);
58
59    std::vector<Function *> Functions;
60    for (auto &F : M.functions()) {
61      Functions.push_back(&F);
62    }
63
64    for (auto &F : Functions) {
65      if (F->isDeclaration())
66        continue;
67
68      const StringRef FName = F->getName();
69
70      if (KNames.count(FName) != 0)
71        continue; // Skip kernels.
72
73      F->replaceAllUsesWith(UndefValue::get((Type *)F->getType()));
74      F->eraseFromParent();
75
76      DEBUG(dbgs() << "Removed:\t" << FName << '\n');
77    }
78
79    // Return true, as the pass modifies module.
80    DEBUG(M.dump());
81    DEBUG(dbgs() << "Done removal\n");
82
83    return true;
84  }
85};
86} // namespace
87
88char RemoveNonkernelsPass::ID = 0;
89
90ModulePass *createRemoveNonkernelsPass(bcinfo::MetadataExtractor &ME) {
91  return new RemoveNonkernelsPass(ME);
92}
93
94} // namespace rs2spirv
95